How to Use Stream Count in Java: Simple Guide
In Java, you can use the
count() method on a Stream to find how many elements it contains. This method returns a long representing the total number of elements in the stream.Syntax
The count() method is called on a Stream object and returns the number of elements in that stream as a long value.
Syntax:
long count = stream.count();Here:
streamis the stream you want to count elements from.count()returns the total number of elements.
java
long count = stream.count();Example
This example shows how to create a list of strings, convert it to a stream, and use count() to find how many items are in the list.
java
import java.util.List; public class StreamCountExample { public static void main(String[] args) { List<String> fruits = List.of("apple", "banana", "cherry", "date"); long count = fruits.stream().count(); System.out.println("Number of fruits: " + count); } }
Output
Number of fruits: 4
Common Pitfalls
One common mistake is calling count() on a stream after it has already been used or closed, which causes an IllegalStateException. Streams can only be used once.
Another pitfall is expecting count() to filter elements; it only counts elements present in the stream at the time of calling.
java
import java.util.List; public class StreamCountPitfall { public static void main(String[] args) { List<String> items = List.of("a", "b", "c"); var stream = items.stream(); System.out.println("Count first time: " + stream.count()); // Uncommenting the next line will cause an error because the stream is already consumed // System.out.println("Count second time: " + stream.count()); } }
Output
Count first time: 3
Quick Reference
- Use:
stream.count()to get the number of elements. - Returns: a
longvalue. - Note: Streams can only be counted once; reuse requires creating a new stream.
Key Takeaways
Use
count() on a stream to get the number of elements as a long value.Streams can only be used once; calling
count() consumes the stream.Create a new stream if you need to count elements multiple times.
count() does not filter elements; it counts what is currently in the stream.It is a simple and efficient way to count elements in collections or other data sources.