The Collectors.counting()
method is a terminal operation that returns the count of elements in the particular stream where it is used. This is part of the java.util.stream.Collectors
in Java 8.
Here is a simple example of how to use Collectors.counting()
. Suppose we have a list of strings, and we want to count the number of elements in it.
package org.kodejava.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsCounting {
public static void main(String... args) {
List<String> names = Arrays.asList("Rosa", "Bob", "Alice", "Dave", "John");
long count = names.stream()
.collect(Collectors.counting());
System.out.println("Count: " + count);
}
}
Output:
Count: 5
In this code:
- We have a list of names.
- We create a stream from this list using the
.stream()
method. - We count the elements of the stream using
.collect(Collectors.counting())
, which returns the number of elements in the stream. - Finally, we print the
count
.
When we run the program, we will get the output “Count: 5”, because there are five elements in the list.
The Collectors.counting()
method is often used in conjunction with other methods like Collectors.groupingBy()
to perform more complex operations like counting the number of elements in each group.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024