Trusted answers to developer questions

What is Collectors.counting() in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

What is the Collectors class?

Collectors is a utility class that provides various implementations of reduction operations such as grouping, collecting, and summarizing elements.

The different functionalities in the Collectors class are used as final operations on streams.

What is the counting() method?

counting() is a static method of the Collectors class that is used to count the number of input elements.

The counting method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package.

To import the Collectors class, we use the following import statement:

import java.util.stream.Collectors;

Syntax


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

Parameters

This method has no parameters.

Return value

This method returns the number of input elements.

Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args)
{
List<String> stringList = Arrays.asList("educative", "io", "edpresso", "educative");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
long numberOfElements = stringStream.collect(Collectors.counting());
System.out.println("Number of elements of the stream - " + numberOfElements);
}
}

Explanation

  • Line 1–4: We import the relevant packages.
  • Line 10: We define a list of strings called stringList.
  • Line 12: We print the stringList.
  • Line 14: We create a stream out of the stringList.
  • Line 16: We count the elements of the stream with the help of the counting method.
  • Line 18: We print the number of elements counted in line 16.

RELATED TAGS

java
counting
collectors
Did you find this helpful?