Java Streams - Collectors counting() example








Collectors counting() returns a Collector accepting elements of type T that counts the number of input elements.

Syntax

counting has the following syntax.

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

Example

The following example shows how to use counting.

import java.util.stream.Collectors;
import java.util.stream.Stream;
//w ww.j  a v a2  s  . com
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("1","2","3");
    
    long o =  s.collect(Collectors.counting());

    System.out.println(o);
    
  }
}

The code above generates the following result.