Java Stream count() Example

1. Introduction

The count() method in Java Streams API is a straightforward and efficient way to count the number of elements in a stream that meet certain criteria. This method is particularly useful for data analysis, where understanding the size of a dataset, or the number of items that match specific conditions, is crucial. Whether you're processing collections of data for business analytics, building inventory systems, or developing social media platforms, count() provides a fundamental tool for quantitative assessment.

Key Points

1. count() is a terminal operation that returns the number of elements in the stream.

2. It can be combined with other stream operations like filter() to count elements that match certain criteria.

3. This method is highly useful for collections processing and should be used judiciously to avoid excessive memory use on large streams.

2. Program Steps

1. Import the necessary Java classes.

2. Create a collection of elements.

3. Convert the collection to a stream and apply any filters.

4. Use count() to count the elements and print the result.

3. Code Program

import java.util.Arrays;
import java.util.List;

public class StreamCountExample {

    public static void main(String[] args) {
        // Step 2: Create a collection of elements
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve", "Frank");

        // Step 3: Apply a filter and use count
        long count =
                          .filter(name -> name.startsWith("A"))

        // Step 4: Print the result
        System.out.println("Number of names starting with 'A': " + count);


Number of names starting with 'A': 1


1. Initialization: The program begins by creating a list of names. This list acts as the basis for the stream operations.

2. Stream Creation and Filtering: A stream is generated from the list, and a filter is applied to only include names that start with the letter "A". This illustrates the integration of filter() with count(), allowing for targeted counting operations.

3. Counting: The count() method calculates the number of elements passing through the stream after filtering. It is a terminal operation, which means it executes the stream pipeline and returns a result.

4. Output: The result of the count is printed, showing how many names start with "A". This simple yet powerful operation is essential for data analysis where counting specific items can provide insights into data trends.

5. Performance Note: count() is an efficient way to determine the size of a dataset, especially when combined with filter(). However, it should be used thoughtfully, particularly with large datasets, as it requires processing all elements that meet the criteria.