$show=/label

Java 8: Counting Matches on a Stream Filter - Stream.count(), Collectors.counting()

SHARE:

Learn how to filter a Stream and count the matches and a quick guide to find the count for a particular condition using filter and map methods of java 8 Stream API.

1. Overview


In this java 8 tutorial, We'll learn how to find the count of a Stream using Stream.count() and Collectors.counting() methods and also how to find the count that matches a specified condition or a Predicate. To use Predicate, we must use the filter() method from Stream API.
Let us start writing a few examples of finding count.

Java 8: Counting Matches on a Stream Filter




2. Stream count syntax

count() method does not take any arguments and simply count as long type.

long count()

Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to the following.

return mapToLong(e -> 1L).sum();

This is part of a terminal operation that means this operation should be in the stream pipeline.

3. Stream count example


First, let us create a Student POJO class with setters and getters.


package com.java.w3schools.blog.java.program.to.java8.stream;

public class Student {

 private int id;
 private String name;
 private int age;

 public Student(int id, String name, int age) {
  super();
  this.id = id;
  this.name = name;
  this.age = age;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public String toString() {
  return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
 }

}


The next step is to create Student objects and add them to an ArrayList. Finally, create a Stream and call count() method. count() method returns the number of objects in the list.


package com.java.w3schools.blog.java.program.to.java8.stream;

import java.util.ArrayList;
import java.util.List;

public class StreamCountExample {

 public static void main(String[] args) {
  Student cena = new Student(200, "Cena Jhon", 35);
  Student jack = new Student(201, "Jack", 40);
  Student ryan = new Student(202, "Ryan", 25);
  Student mithai = new Student(203, "Mithai", 17);
  Student paul = new Student(204, "Paul", 15);

  List<Student> students = new ArrayList<>();
  students.add(cena);
  students.add(jack);
  students.add(ryan);
  students.add(mithai);
  students.add(paul);

  long stuCount = students.stream().count();

  System.out.println("Students count: " + stuCount);

 }

}

Output:

Students count: 5

4. Stream count() and filter() predicate example


In the above program is simple that directly uses count() method. That is a very rare scenario. Instead of using Stream.count(), you can directly use the list.size() method that produces the same result.

Let us perform some criteria to filter the Student objects using the filter() method.

package com.java.w3schools.blog.java.program.to.java8.stream;

import java.util.Arrays;
import java.util.List;

public class StreamCountFilterExample {

 public static void main(String[] args) {
  Student cena = new Student(200, "Cena Jhon", 35);
  Student jack = new Student(201, "Jack", 40);
  Student ryan = new Student(202, "Ryan", 25);
  Student mithai = new Student(203, "Mithai", 17);
  Student paul = new Student(204, "Paul", 15);

  List<Student> students = Arrays.asList(cena, jack, ryan, mithai, paul);

  long elegibleStudents = students.stream().filter(s -> s.getAge() > 18).count();

  System.out.println("Eligible Students count: " + elegibleStudents);

 }

}

Output:


Eligible Students count: 3

This program has filtered 2 students whose age is less than 20 years. We will see the shine and power of count() method really when to combine with other Streams API methods such as filter() and map() methods.

Apply the same logic for students age > 40 years.

long ageGreaterThan40Years = students
         .stream()
         .filter(s -> s.getAge() > 40)
         .count();

System.out.println("Age > 40 years students: " + ageGreaterThan40Years);

Output:

Age > 40 years students: 0

5. Stream filter count java 8 with advanced filters

We can add multiple filters to the stream api.

long multipleFilterCount = students
         .stream()
         .filter(s -> s.getAge() > 20 && s.getName().contains("c"))
         .count();

6. count() and filter() methods with Method Reference

We can apply the Method Reference concept in the filter so that its logic can be reused.

package com.java.w3schools.blog.java.program.to.java8.stream;

import java.util.Arrays;
import java.util.List;

public class StreamCountFilterExample {

 public static void main(String[] args) {
  Student cena = new Student(200, "Cena Jhon", 35);
  Student jack = new Student(201, "Jack", 40);
  Student ryan = new Student(202, "Ryan", 25);
  Student mithai = new Student(203, "Mithai", 17);
  Student paul = new Student(204, "Paul", 15);

  List<Student> students = Arrays.asList(cena, jack, ryan, mithai, paul);


  long methodRefFilterCount = students
           .stream()
           .filter(StreamCountFilterExample::validateAgeAndName)
           .count();

  System.out.println("Method Ref filters count: "+methodRefFilterCount);
  
 }
 
 public static boolean validateAgeAndName(Student student) {
  
  return student.getAge() > 20 && student.getName().contains("c");
  
 }

}

Output:

Method Ref filters count: 1

7. Finding count using Collectors.counting()


As of now, we have seen many examples using stream.count() method using filter() combinations and method reference. But, Collectors API also provided with a similar kind of method counting() which is a static utility method.

7.1 Syntax


public static <T> Collector<T,?,Long> counting()

This is a public and static method so we can access it directly with the class name. This method returns a long type.

7.2 Example


package com.java.w3schools.blog.java.program.to.java8.stream;

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamCollectorsCountingExample {

 public static void main(String[] args) {

  // Counting Strings present in the stream
  long strCount = Stream
         .of("Java", "program", "to", "com", "java-w3schools")
         .collect(Collectors.counting());
  System.out.printf("There are %d strings in the stream %n", strCount);

  // Counting numbers in stream
  long numbersCount = Stream
        .of(1, 2, 3, 4, 5, 6, 7, 8, 9)
        .collect(Collectors.counting());
  System.out.printf("There are %d numbers in the stream %n", numbersCount);

  // counting() method with filter()
  long evenCount = Stream
        .of(1, 2, 3, 4, 5, 6, 7, 8, 9)
        .filter(i -> i % 2 == 0)
        .collect(Collectors.counting());
  System.out.printf("Even numbers count: "+evenCount);
 }
}

Output:

There are 5 strings in the stream 
There are 9 numbers in the stream 
Even numbers count: 4  

8. Conclusion


In this article, We have seen how to find the count of the stream using Stream.count() and Collectos.counting() methods. Examples are shown with a Predicate filter and multiple filters.
At last, shown example using Method Reference.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8: Counting Matches on a Stream Filter - Stream.count(), Collectors.counting()
Java 8: Counting Matches on a Stream Filter - Stream.count(), Collectors.counting()
Learn how to filter a Stream and count the matches and a quick guide to find the count for a particular condition using filter and map methods of java 8 Stream API.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8GTdF5d6NCTgCxru0bOkdwtXIKuTxTfHAbvIarnbP0jykqzW5d8wco5B1h5vKt_0hqdZzYG59mFNGWbhyphenhyphens60eqIKqQXs0h4rTaBVm4L8EHbzSS81pX4whWgOQFtoEFySL8jDy1p6gy7s/s640/Java+8+Counting+Matches+on+a+Stream+Filter.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8GTdF5d6NCTgCxru0bOkdwtXIKuTxTfHAbvIarnbP0jykqzW5d8wco5B1h5vKt_0hqdZzYG59mFNGWbhyphenhyphens60eqIKqQXs0h4rTaBVm4L8EHbzSS81pX4whWgOQFtoEFySL8jDy1p6gy7s/s72-c/Java+8+Counting+Matches+on+a+Stream+Filter.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/01/java-stream-filter-count.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/01/java-stream-filter-count.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content