Saturday, September 10, 2016

Stream Interface anyMatch method

Stream Interface anyMatch method

In this post we will see anyMatch method of Stream interface. anyMatch method is similar to filter and allMatch method in terms of parameter. They all accept Predicate.

The method name provides the explanation itself. It says that if any element is matched in Stream with this predicate then return true else return false. anyMatch is a terminal operation that uses short-circuiting i.e. if any element matches the predicate it returns result rather than comparing other elements.

Below is the method declaration provided in Stream<T> interface.

    boolean anyMatch(Predicate<? super T> predicate);

anyMatch method may not evaluate the Predicate on all elements if not necessary for determining the result. This means that any matching criteria is done by short circuiting operator. So if any element is evaluated to true by Predicate than other elements are not checked by Predicate as it is not needed.

Let us take simple example and understand this method. Given us List of names find out if any name start with “J”. Below is the code.

List<String> names = new ArrayList<>();
names.add("John");
names.add("Jane");
names.add("Arya");
names.add("Sansa");
             
final boolean anyNameStartsWithJ =
              names.stream()
                   .anyMatch(name -> name.startsWith("A")); //returns true.

final boolean anyNameStartsWithJ =
              names.stream()
                   .anyMatch(name -> name.startsWith("S")); //returns true.

final boolean anyNameStartsWithJ =
              names.stream()
                   .anyMatch(name -> name.startsWith("Z")); //returns false.

If the stream is empty, then anyMatch is always evaluated to false regardless of Predicate supplied in argument as Predicate is not executed.


That’s all on anyMatch method. In next post we will see noneMatch method. noneMatch method returns true if none of the elements in stream matches the given Predicate.

Ads Inside Post