Collectors.counting to count total elements
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorCountFlight {
public static void main(String[] args) {
long totalNumbers = Stream.of(1,2,3,4,5,6,7,8,9).count();
System.out.println("1) Total Numbers: "+totalNumbers);
Stream<Integer> numStream = Stream.of(1,3,4,5,6,7,45,6,9);
long totalNums = numStream.collect(Collectors.counting());
System.out.println("2) Total Numbers "+totalNums);
}
}
Output:
1) Total Numbers: 9
2) Total Numbers: 9
Explanation:
You can count total elements .count() method on the stream or using the Collectors.counting()
public static <T> Collector<T, ?, Long> counting():
Returns a Collector accepting elements of type T that counts the number of input elements in the Stream. If no elements are present, the result is 0.
The counted value is returned in a long.Long type.