Java Stream allMatch()

In this post, we are going to see the Java Stream allMatch() method example.

The allMatch() method in Java is a terminal operation provided by the Stream API that tests whether all elements of a stream match a given predicate. It returns a boolean value indicating whether all elements in the stream satisfy the condition specified by the predicate. If the stream is empty, it returns true since there are no elements to check.

Syntax of Java Stream allMatch() method

boolean allMatch(Predicate<? super T> predicate)

Here’s an example of how to use allMatch() with Java streams:

import java.util.List;
import java.util.stream.Stream;

public class StreamAllMatchExample {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = List.of(2, 4, 6, 8, 10);

        // Use a stream to check if all numbers are even
        boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);

        // Print the result
        if (allEven) {
            System.out.println("All numbers are even.");
        } else {
            System.out.println("Not all numbers are even.");
        }

        // Another example with strings
        List<String> words = List.of("apple", "banana", "cherry", "date");

        // Use a stream to check if all words start with the letter 'a'
        boolean allStartWithA = words.stream().allMatch(word -> word.startsWith("a"));

        // Print the result
        if (allStartWithA) {
            System.out.println("All words start with 'a'.");
        } else {
            System.out.println("Not all words start with 'a'.");
        }
    }
}

Output:-

All numbers are even.
Not all words start with 'a'.

Java Stream allMatch() exmaples

Let’s see five different use cases for the Java Stream allMatch() method.

  1. Checking if all employees in a list have a salary greater than a certain threshold:
import java.util.List;

public class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    public static void main(String[] args) {
        List<Employee> employees = List.of(
            new Employee("Alice", 50000),
            new Employee("Bob", 60000),
            new Employee("Charlie", 75000)
        );

        boolean allHighEarners = employees.stream().allMatch(e -> e.getSalary() > 60000);

        if (allHighEarners) {
            System.out.println("All employees are high earners.");
        } else {
            System.out.println("Not all employees are high earners.");
        }
    }
}

Output:

Not all employees are high earners.
  1. Checking if all elements in a list of strings are of the same length:
import java.util.List;

public class StringLengthExample {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "banana", "cherry", "date");

        boolean allSameLength = words.stream().allMatch(word -> word.length() == 5);

        if (allSameLength) {
            System.out.println("All words have a length of 5 characters.");
        } else {
            System.out.println("Not all words have a length of 5 characters.");
        }
    }
}

Output:

Not all words have a length of 5 characters.
  1. Checking if all elements in an array of integers are positive:
import java.util.Arrays;

public class PositiveNumbersExample {
    public static void main(String[] args) {
        int[] numbers = { 1, 3, 5, 7, 9 };

        boolean allPositive = Arrays.stream(numbers).allMatch(n -> n > 0);

        if (allPositive) {
            System.out.println("All numbers are positive.");
        } else {
            System.out.println("Not all numbers are positive.");
        }
    }
}

Output:

All numbers are positive.
  1. Verifying if all elements in a list of booleans are true:
import java.util.List;

public class BooleanListExample {
    public static void main(String[] args) {
        List<Boolean> flags = List.of(true, true, true, true);

        boolean allTrue = flags.stream().allMatch(Boolean::booleanValue);

        if (allTrue) {
            System.out.println("All elements are true.");
        } else {
            System.out.println("Not all elements are true.");
        }
    }
}

Output:

All elements are true.
  1. Checking if all elements in a list are equal to a specific value:
import java.util.List;

public class ElementEqualityExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 5, 5, 5, 5);

        boolean allFives = numbers.stream().allMatch(n -> n == 5);

        if (allFives) {
            System.out.println("All elements are equal to 5.");
        } else {
            System.out.println("Not all elements are equal to 5.");
        }
    }
}

Output:

All elements are equal to 5.

These examples demonstrate different use cases for the allMatch() method with various types of data and conditions, along with the expected output based on the evaluation of the provided predicates.

Summary:-

  1. Purpose and Usage:
  • allMatch() is a terminal operation provided by the Stream API in Java 8 and later versions.
  • It is used to check whether all elements of a stream satisfy a given condition (predicate).
  1. Predicate Function:
  • allMatch() takes a predicate function as its argument. The predicate is a lambda expression or method reference that defines the condition to be checked against each element in the stream.
  • The predicate should return a boolean value indicating whether an element matches the condition.
  1. Return Value:
  • allMatch() returns a boolean result:
    • true if all elements in the stream satisfy the specified condition (predicate) without any exceptions.
    • false if at least one element in the stream does not meet the condition, or if the stream is empty.
  1. Short-Circuiting:
  • One of the key features of allMatch() is short-circuiting behavior. If the predicate evaluates to false for any element in the stream, the method immediately returns false without processing the remaining elements. This can be more efficient for large streams.
  1. Common Use Cases:
  • Common use cases for allMatch() include checking if:
    • All elements in a collection meet a specific criteria (e.g., all numbers are positive).
    • All elements in a stream share a common property (e.g., all names start with a certain letter).
    • All elements in a stream belong to a particular category (e.g., all employees have a certain job title).
    Remember to use allMatch() when you want to ensure that a condition holds for every element in the stream.

Ten objective questions related to the Java Stream allMatch()

Question 1: What is the purpose of the allMatch() method in Java 8 streams?

A) To return the first element of the stream.
B) To check if all elements in a stream match a given condition.
C) To count the number of elements in a stream.
D) To map elements in a stream to a new stream.

Question 2: What type of function does allMatch() take as its argument?

A) Consumer
B) Predicate
C) Function
D) Supplier

Question 3: What does the allMatch() method return if at least one element in the stream does not satisfy the condition?

A) true
B) false
C) An exception is thrown.
D) null

Question 4: Which behavior describes the short-circuiting feature of allMatch()?

A) It processes all elements in the stream even if the condition fails for the first element.
B) It immediately returns false if the condition fails for any element.
C) It converts the stream into a list.
D) It reverses the order of elements in the stream.

Question 5: In a stream of integers, what does the following code check?

boolean allPositive = intStream.allMatch(n -> n > 0);

A) If all integers are even.
B) If all integers are positive.
C) If at least one integer is positive.
D) If the stream is empty.

Question 6: Which of the following statements is true about the allMatch() method?

A) It can only be used with parallel streams.
B) It can be used to transform elements in a stream.
C) It returns a collection of matching elements.
D) It returns a boolean result indicating if all elements match the condition.

Question 7: When is the allMatch() method most efficient for large streams?

A) When the stream is empty.
B) When the condition is complex.
C) When the predicate always returns true.
D) When short-circuiting occurs early in the stream.

Question 8: What is the result of the following code?

Stream<String> words = Stream.of("apple", "banana", "cherry");
boolean allShort = words.allMatch(word -> word.length() < 10);

A) true
B) false
C) Compilation error
D) An exception is thrown.

Question 9: How does the allMatch() method behave with an empty stream?

A) It returns true because there are no elements to match.
B) It returns false because there are no elements to match.
C) It throws an exception.
D) It depends on the condition specified.

Question 10: Which of the following is a common use case for the allMatch() method?

A) Finding the sum of all elements in a stream.
B) Checking if all elements in a stream meet a specific condition.
C) Sorting the elements in a stream.
D) Transforming elements in a stream to uppercase.

Answers:

  1. B
  2. B
  3. B
  4. B
  5. B
  6. D
  7. D
  8. A
  9. A
  10. B

Summary:-

  1. Purpose and Usage:
  • allMatch() is a terminal operation provided by the Stream API in Java 8 and later versions.
  • It is used to check whether all elements of a stream satisfy a given condition (predicate).
  1. Predicate Function:
  • allMatch() takes a predicate function as its argument. The predicate is a lambda expression or method reference that defines the condition to be checked against each element in the stream.
  • The predicate should return a boolean value indicating whether an element matches the condition.
  1. Return Value:
  • allMatch() returns a boolean result:
    • true if all elements in the stream satisfy the specified condition (predicate) without any exceptions.
    • false if at least one element in the stream does not meet the condition, or if the stream is empty.
  1. Short-Circuiting:
  • One of the key features of allMatch() is short-circuiting behavior. If the predicate evaluates to false for any element in the stream, the method immediately returns false without processing the remaining elements. This can be more efficient for large streams.
  1. Common Use Cases:
  • Common use cases for allMatch() include checking if:
    • All elements in a collection meet a specific criteria (e.g., all numbers are positive).All elements in a stream share a common property (e.g., all names start with a certain letter).All elements in a stream belong to a particular category (e.g., all employees have a certain job title).
    Remember to use allMatch() when you want to ensure that a condition holds for every element in the stream.

That’s all about Java Stream allMatch() method.

Other Java 8 Stream tutorials.