How do I use Collectors.counting() method?

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.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.