Java Stream allMatch()

In this guide, you will learn about the Stream allMatch() method in Java programming and how to use it with an example.

1. Stream allMatch() Method Overview

Definition:

The Stream.allMatch() method is a terminal operation that returns a boolean indicating whether all elements of the stream match the given predicate. It's often used to determine if every element in the stream satisfies a particular condition.

Syntax:

boolean allMatch(Predicate<? super T> predicate)

Parameters:

- predicate: a non-interfering, stateless predicate to apply to elements of the stream.

Key Points:

- It's a terminal operation, which means it ends the pipeline and you cannot reuse the stream afterward.

- The method returns a boolean value.

- Like anyMatch(), it's a short-circuiting operation. It stops processing as soon as it finds an element that doesn't match the condition.

- If the stream is empty, then the result is true (considered vacuously true, because no elements failed to match the predicate).

- It processes elements in the order they appear until it finds a non-matching element or all elements have been processed.

2. Stream allMatch() Method Example

import java.util.stream.Stream;

public class StreamAllMatchExample {
    public static void main(String[] args) {
        Stream<String> fruitStream = Stream.of("apple", "banana", "cherry", "date", "elderberry");

        // Check if all fruit names have more than 4 characters
        boolean allFruitsHaveMoreThan4Chars = fruitStream.allMatch(fruit -> fruit.length() > 4);

        System.out.println("Do all fruit names have more than 4 characters? " + allFruitsHaveMoreThan4Chars);
    }
}

Output:

Do all fruit names have more than 4 characters? true

Explanation:

In the provided example: We have a stream of fruit names. Using allMatch(), we check if every fruit name has more than 4 characters. Since each name in the stream ("apple", "banana", "cherry", "date", "elderberry") has a length greater than 4, the result is true.

Comments