Close

Java 8 Streams - Collectors.counting Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.Collectors

java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

Method:

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

Returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.


Examples


The method Collectors#counting collects the counts of the stream elements.

package com.logicbig.example.collectors;

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountingExample {
public static void main (String[] args) {
Stream<String> s = Stream.of("apple", "banana", "orange");
Long c = s.collect(Collectors.counting());
System.out.println(c);
}
}

Output

3
Original Post




See Also