Java Stream allMatch() Example

1. Introduction

The allMatch() method in Java Streams is a terminal operation that checks if every element in a stream matches a given predicate. It's an efficient way to validate all elements of a collection against a single condition, useful in data validation, integrity checks, or filtering processes where a collective attribute needs to be confirmed across an entire dataset.

Key Points

1. allMatch() returns a boolean value indicating whether all elements in the stream satisfy the specified predicate.

2. It is a short-circuiting terminal operation that stops processing as soon as a false condition is found.

3. This method is ideal for ensuring that a dataset conforms to a particular requirement or rule.

2. Program Steps

1. Import necessary classes.

2. Create a collection of elements.

3. Convert the collection into a stream and apply the allMatch() method.

4. Print the result to display whether all elements match the condition.

3. Code Program

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

public class StreamAllMatchExample {

    public static void main(String[] args) {
        // Step 2: Create a collection of elements
        List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);

        // Step 3: Apply allMatch to determine if all numbers are even
        boolean allEven = numbers.stream()
                                 .allMatch(num -> num % 2 == 0);

        // Step 4: Print the result
        System.out.println("Are all numbers even? " + allEven);
    }
}

Output:

Are all numbers even? true

Explanation:

1. The program initializes a List of integers. Here, the list consists solely of even numbers.

2. It then creates a stream from this list. The allMatch() method is applied with a lambda expression num -> num % 2 == 0 that checks if a number is even.

3. allMatch() iterates over each element in the stream, applying the lambda expression. If all elements satisfy the condition (i.e., are even in this case), it returns true. If any element does not satisfy the condition, it would return false.

4. The result, true, is then printed, indicating that all numbers in the list are even. This confirms the functionality of allMatch() for verifying uniform properties across all elements in a collection.

5. Using allMatch() is particularly advantageous in scenarios requiring a comprehensive validation of elements, where the goal is to ensure that every element adheres to a specific criterion, thereby maintaining consistency and integrity of data.


Comments