Java Stream How to - Count element in Stream








Question

We would like to know how to count element in Stream.

Answer

/*  w  w w .  j a v  a  2  s.  c  om*/
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) {
    System.out.println("counting " +
        Arrays.asList(1,20,40,4)
        .stream()
        .collect(Collectors.counting()));
  }
}

The code above generates the following result.