Junior — Middle
Is it possible to determine and get the total number of elements passing through a Stream?
sobes.tech AI
Answer from AI
Yes, in Java Stream API, you can define and obtain the total number of elements passing through the Stream using the terminal operation count(). It returns the number of elements in the stream.
Example:
List<String> list = Arrays.asList("a", "b", "c");
long count = list.stream().count();
System.out.println(count); // Outputs 3
It is important to remember that after a terminal operation, the stream becomes closed and cannot be used again.