Friday, August 12, 2016

Stream Interface allMatch method

Stream interface allMatch method

This is 8th post in Java Stream category. We have done Stream Introduction, getting started with streams, terminal and intermediate operations in stream. Then we saw one-line description of all methods of stream interface. Here is complete list of Streams post that we saw.

In this post we will see another method of Stream interface called allMatch(). This is a terminal operation on Stream means this operation returns a non-stream result.

Below is method declaration provided in java.util.stream

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

allMatch method returns true if all the elements in stream matches the given predicate else it returns false. If the stream is empty, then it returns true and predicate is not evaluated.

allMatch method may not evaluate the Predicate on all elements if not necessary for determining the result. This means that all matching criteria is done by short circuiting operator. So if one element is evaluated to false 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 all names start with “J”. Below is the code.

List<String> names = new ArrayList<String>();
names.add("John");
names.add("Jane");
names.add("Jonny");
names.add("Jack");
names.add("Jackie");

final boolean namesStartsWithJ =
                    names.stream()
                         .allMatch(new Predicate<String>() {
                                    public boolean test(String name) {
                                           return name.startsWith("J");
                                  };
                         });
System.out.println("Does all names start with J: " + namesStartsWithJ);


The above code returns true. In above code allMatch method uses Predicate interface as anonymous inner class. We will use the lambda operator as below as Predicate interface is functional interface. 

final boolean namesStartsWithJ = names.stream()
                                      .allMatch(name -> name.startsWith("J"));

If the stream is empty, then allMatch is always evaluated to true regardless of a Predicate supplied in argument.

That's all on allMatch method. In next post we will see anyMatch method. anyMatch method returns true if any element in stream matches the given Predicate.

No comments:

Post a Comment

Ads Inside Post