What is the noneMatch() method of Stream Interface in Java?

The noneMatch method of Stream Interface can be used to check if no elements of the stream match/satisfy the provided PredicatePredicate is a Functional interface that takes one argument and returns either true or false based on the condition defined..

The noneMatch method is a short-circuiting terminal operation:

  • It will return true if the stream is empty.
  • Additionally, if an element matches the Predicate, then the noneMatch method will return false without the application of the Predicate function on the remaining elements on the stream.

Syntax

boolean noneMatch(Predicate<? super T> predicate)

Argument

The noneMatch method takes a Predicate function as an argument.

Return value

The method returns true if all the elements in the stream don’t match the provided Predicate.

The method returns false if any one of the elements matches the provided Predicate.

Example

import java.util.ArrayList;
class NoneMatchTest {
public static void main( String args[] ) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("The numbers list is " + numbers);
boolean isPositiveList;
isPositiveList = numbers
.stream()
.noneMatch((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()
.noneMatch((number) -> number < 0 );
System.out.println("All numbers on the List is positive - " + isPositiveList);
}
}

In the code above, we have:

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

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

  • Added -1to the ArrayList, and again called the noneMatch method on the ArrayList. Now, the list contains one element, which matches the Predicate function. In this case, the noneMatch method will return false.

Free Resources