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.
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.
This is part of a terminal operation that means this operation should be in the stream pipeline.
First, let us create a Student POJO class with setters and getters.
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.
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.
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.
Output:
Output:
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.
This is a public and static method so we can access it directly with the class name. This method returns a long type.
Output:
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.
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.
No comments:
Post a Comment
Please do not add any spam links in the comments section.