Java Stream count() Example

1. Introduction

This tutorial will explain how to use the count() method in Java's Stream API. The count() method is a terminal operation that returns the count of elements in the stream. It is useful for determining the number of elements that meet certain criteria or simply counting the total elements in a stream.

Key Points

1. count() returns the number of elements in the stream as a long value.

2. It is a terminal operation, which means after its execution, the stream can no longer be used.

3. count() is often used after filtering or mapping operations to determine the size of the resultant stream.

2. Program Steps

1. Create a Stream of elements.

2. Optionally apply filters or transformations.

3. Use count() to get the number of elements in the stream.

3. Code Program

import java.util.stream.Stream;

public class StreamCountExample {

    public static void main(String[] args) {
        // Stream of numbers
        Stream<Integer> numberStream = Stream.of(1, 2, 3, 4, 5);

        // Count the elements in the stream
        long count = numberStream.count();
        System.out.println("Count of numbers: " + count);

        // Stream of strings with filter
        Stream<String> stringStream = Stream.of("apple", "banana", "cherry", "date", "elderberry", "fig");

        // Count strings with more than 5 characters
        long countLongNames = stringStream.filter(s -> s.length() > 5).count();
        System.out.println("Count of strings longer than 5 characters: " + countLongNames);
    }
}

Output:

Count of numbers: 5
Count of strings longer than 5 characters: 3

Explanation:

1. Stream.of(1, 2, 3, 4, 5) creates a stream of integers.

2. numberStream.count() calculates the total number of elements in the stream, which is then printed.

3. Stream.of("apple", "banana", "cherry", "date", "elderberry", "fig") creates another stream, this time of strings.

4. stringStream.filter(s -> s.length() > 5) filters the strings to only those longer than five characters.

5. countLongNames stores the count of these filtered strings and is then printed, showing how many strings are longer than five characters.

Comments