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.
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;
public static <T> Collector<T, ?, Long> counting()
This method has no parameters.
This method returns the number of input elements.
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);}}
stringList
.stringList
.stringList
.counting
method.