Java Stream allMatch()

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare