Java streams 20. AnyMatch, allMatch, or noneMatch

Terminal operations either return values (of the same or other types) or do not return anything at all (produce just side effects). They do not allow other operations to be applied and close the stream.

Today we will cover three terminal operations, each returning a boolean value:

boolean allMatch(Predicate<T> predicate). Returns true if the provided Predicate<T> function returns true when applied to each of the elements produced by the Stream object. Otherwise, returns false–if one of the elements yields false when used as an input to the provided Predicate<T> function. 

boolean anyMatch(Predicate<T> predicate). Returns true if the provided Predicate<T> function returns true when applied to one of the elements produced by the Stream object. Otherwise, returns false–if each of the elements yields false when used as an input to the provided Predicate<T> function. 

boolean noneMatch(Predicate<T> predicate). Returns true if the provided Predicate<T> function returns false when applied to each of the elements produced by the Stream object. Otherwise, returns false–if one of the elements yields true when used as an input to the provided Predicate<T> function. 

Here are the examples of these operations usage:

  
  List<String> list = List.of("1", "2", "3", "4", "5");

  boolean found = list.stream()
        .peek(System.out::print)          //prints: 1
        .allMatch(e -> "3".equals(e));
  System.out.println("\n" + found);       //prints: false

  boolean found = list.stream()
        .peek(System.out::print)          //prints: 123
        .anyMatch(e -> "3".equals(e));
  System.out.println("\n" + found);       //prints: true

  boolean found = list.stream()
        .peek(System.out::print)          //prints: 123
        .noneMatch(e -> "3".equals(e));
  System.out.println("\n" + found);       //prints: false

As you have probably noticed, these operations are optimized so as not to process all the stream elements but return a result as soon as it can be determined.

In the next post, before presenting the next group of terminal operations, we will discuss the class Optional<T>, which is used as a returned value of some operations.

See other posts on Java 8 streams and posts on other topics.
You can also use navigation pages for Java stream related blogs:
— Java 8 streams blog titles
— Create stream
— Stream operations
— Stream operation collect()
The source code of all the code examples is here in GitHub

, ,

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes