Java streams counting() method with examples


Count the number of elements in the stream using the Java streams counting() method. Following is an example to implement the Java Streams counting() method −

Example

 Live Demo

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam");
      // count
      long count = stream.collect(Collectors.counting());
      System.out.println("Number of elements in the stream = "+count);
   }
}

Output

Number of elements in the stream = 5

Let us see another example wherein we have stream of integer elements −

Example

 Live Demo

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<Integer> stream = Stream.of(5, 10, 20, 40, 80, 160);
      // count
      long count = stream.collect(Collectors.counting());
      System.out.println("Number of elements in the stream = "+count);
   }
}

Output

Number of elements in the stream = 6

Updated on: 26-Sep-2019

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements