What is the allMatch method of the Stream Interface?

The allMatch method of the Stream Interface can be used to check if all elements of the stream match/satisfy the provided predicatePredicate is a functional interface, which takes one argument and returns either true or false based on the condition defined..

The allMatch method is a short-circuiting terminal operation.

  • It will return true if the stream is empty.
  • If an element doesn’t match the predicate, then the allMatch method will return false without applying the Predicate function to the stream’s remaining elements.

Syntax

boolean allMatch(Predicate<? super T> predicate)

Parameters

The allMatch method takes a Predicate function as an argument.

Return value

  • true: If all the elements in the stream match the given Predicate.

  • false: If any one of the elements doesn’t match the provided Predicate.

Code

import java.util.ArrayList;
class AllMatchTest {
public static void main( String args[] ) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("The numbers list is " + numbers);
boolean isPositiveList;
isPositiveList = numbers
.stream()
.allMatch((number) -> number > 0 );
System.out.println("All numbers on the List is positive - " + isPositiveList);
numbers.add(-1);
System.out.println("\nAdded -1 to the numbers list now the list is - " + numbers);
isPositiveList = numbers
.stream()
.allMatch((number) -> number > 0 );
System.out.println("All numbers on the List is positive - " + isPositiveList);
}
}

Explanation

In the code above, we:

  • Created an ArrayList with the elements:
1,2,3
  • From the ArrayList, we use the stream() function to get the stream of the ArrayList.

  • Called the allMatch method with a Predicate function. In the Predicate function, we check if the value is > 0. The allMatch method will loop through all the elements of the stream and test each element against the passed Predicate function. In our case, all elements match the Predicate function because all the elements in the list are > 0. So, true is returned from the allMatch method.

  • Added -1 to the ArrayList, and called the allMatch method on the ArrayList. Now, the list contains one element (-1) which doesn’t match the Predicate function. In this case, the allMatch method returns false.

Free Resources