Wednesday, February 1, 2023

How to use Stream allMatch() and anyMatch() function in Java? Example Tutorial

Hello friends, we all know how streams are super important for our day-to-day needs in Java programming and coding nowadays. It allows us to filter data in memory in a declarative way, it also allows us to transform objects as well create a complex Stream pipeline to represent our business logic in a declarative fashion. But, do we know all the stream functionalities? Of course not. Earlier, we have seen examples of filter(), map, flatMap, and findFirst() method and today we will learn two of the most important stream functions anyMatch() and allMatch().  So what’s the wait? Let's start!




Stream allMatch: 


We often run into problems where we need to check a condition on a list of values. To give an example, let’s say there’s an array with 500 objects and we need to check if each one of them is divisible by 3 or not. 


Now, the normal way is to run a loop through the array and check the condition for all objects. But wait, why so much boilerplate code? We can use streams and this would be completed in just a single line! Yes, that’s true.


How to use Stream allMatch and anyMatch in Java? Example Tutorial




The syntax of the Stream allMatch function is as below:


allMatch(Predicate predicate) 


Here, the predicate is the condition on which each element will be checked. We can also provide multiple such predicates to stream. Below is a working example of how the function works. 


As shown in the code, we can see how it works. we have an array of size 5 with different numbers inside it. we convert it to Stream using Arrays.stream() function


We have used IntPredicate. similarly, we can use different types of Predicates.





Stream allMatch code:


import java.util.Arrays;
import java.util.function.IntPredicate;

public class StreamExample {

public static void main(String[] args) {
int[] arr = new int[] {3, 18, 15, 30, 60};

IntPredicate isDivisibleByThree = a -> (a%3 == 0);
IntPredicate isDivisibleByFive = a -> (a%5 == 0);

IntPredicate isDivisibleByThreeAndFive = isDivisibleByThree
.and(isDivisibleByFive);

boolean isDivisibleByThreeResult = Arrays.stream(arr)
.allMatch(isDivisibleByThree);
System.out.println("divisible by three: "+isDivisibleByThreeResult);
boolean isDivisibleByFiveResult = Arrays.stream(arr)
.allMatch(isDivisibleByFive);
System.out.println("divisible by five: "+isDivisibleByFiveResult);
boolean isDivisibleByThreeAndFiveResult = Arrays.stream(arr)
.allMatch(isDivisibleByThreeAndFive);
System.out.println("divisible by three and five: "
+isDivisibleByThreeAndFiveResult);

}

}


Output:





As see, we had multiple predicates on it and it gave us results successfully. The predicate can be any complex operation too. I have demonstrated using integers, you guys can try hands-on for char or objects too. I have used IntPredicate. For objects, you can use Predicate<YourObject> too.




Stream anyMatch:


Now, after observing the above code, you guys must be pretty confident about what stream anyMatch does. anyMatch basically searches the array/list or any collection for any match. Just 1 is enough for the answer to be true. 


So continuing our previous code and example, let’s understand how this happens. But before that, let’s see the syntax of stream anyMatch


The syntax of stream anyMatch is as below: 


anyMatch(Predicate predicate)


Here, the predicate is the condition on which each element will be checked. We can also provide multiple such predicates to stream. Below is a working example of how the function works. Extending and reusing our previous example.


Let's use the same array and see what happens with the anyMatch function.





Stream anyMatch code:


import java.util.Arrays;
import java.util.function.IntPredicate;

public class StreamExample {

public static void main(String[] args) {
int[] arr = new int[] {3, 18, 15, 30, 60};

IntPredicate isDivisibleByThree = a -> (a%3 == 0);
IntPredicate isDivisibleByFive = a -> (a%5 == 0);

IntPredicate isDivisibleByThreeAndFive = isDivisibleByThree
.and(isDivisibleByFive);

boolean isDivisibleByThreeResult = Arrays.stream(arr)
.anyMatch(isDivisibleByThree);
System.out.println("divisible by three: "+isDivisibleByThreeResult);
boolean isDivisibleByFiveResult = Arrays.stream(arr)
.anyMatch(isDivisibleByFive);
System.out.println("divisible by five: "+isDivisibleByFiveResult);
boolean isDivisibleByThreeAndFiveResult = Arrays.stream(arr)
.anyMatch(isDivisibleByThreeAndFive);
System.out.println("divisible by three and five: "
+isDivisibleByThreeAndFiveResult);

}

}


Output:





So now, you guys must know how Stream API's allMatch() and anyMatch() function works. But, there are a few points to keep in mind before using these functions.


First of all, take 2 minutes and brainstorm over any thoughts and think what would happen if the stream is infinite.


How will these functions handle them? Also think that if objects are passed, what if the desired fields are not present or null or empty?


Take 2 minutes and think over these questions and then we will discuss each of them.





Important points to remember:

  1. What if the stream is empty? anyMatch - false, allMatch - true. There is the answer returned is the streams are empty.
  2. Both functions are short-circuiting terminal operations. This means, if an infinite stream is presented, the functions may terminate in finite time.

Stream.allMatch()  returns true for empty stream and anyMatch returns false. This may sound a little bit confusing. but no worries friends, we are here to solve all the queries and questions.
allMatch()  returns true. 

This is known as vacuous truth. All members of an empty collection satisfy your condition; after all, can you point to one that doesn't?


Similarly, anyMatch returns false, because you can't find an element of your collection that does match the condition. This is confusing to a lot of people, but it turns out to be the most useful and consistent way to define "any" and "all" for empty sets.

Hope you guys enjoyed the lesson! let's meet in our next article.


Other Java 8  Lambda and Stream Tutorials You may like

Thanks for reading this tutorial so far. If you like this Java 8 Stream allMatch() and anyMatch() example tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are keen to learn Java 8 Functional programming but looking for a free online training course to start with then you can also check out this Java 8 Functional Programming: Lambda Expressions Quickly course on Udemy. It's completely free and you just need a Udemy account to join this course. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.