In this tutorial, we will see “How to use allMatch vs anyMatch methods in a Stream in Java 8” with most simplest examples so that even beginners can understand with ease. In Java 8, the Stream
interface provides two methods to check if all or any elements in a stream match a given predicate: allMatch
and anyMatch
.
Java 8 stream allmatch vs anymatch
allMatch()
Here is an example of using allMatch
to check if all elements in a stream of integers are greater than 10:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /** * Using allMatch to check if all elements in a stream of integers are greater than 10 * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; public class AllMatch_Java8Stream_Example { public static void main(String args[]) { List<Integer> listOfNumbers = Arrays.asList(5, 15, 20, 25, 30, 35, 40, 45, 50); boolean allGreaterThan10 = listOfNumbers.stream().allMatch(x -> x > 10); System.out.println("List: "+listOfNumbers.toString()); System.out.println("Are all numbers present in the list greater than 10?: "+allGreaterThan10); } } |
Output:
1 2 | List: [5, 15, 20, 25, 30, 35, 40, 45, 50] Are all numbers present in the list greater than 10?: false |
anyMatch()
And, here is an example of using anyMatch
to check if any element in a stream of strings is equal to “Techndeck”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * Using anyMatch to check if any element in a stream of strings is equal to "Techndeck": * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; public class AllMatch_Java8Stream_Example { public static void main(String args[]) { List<String> listOfStrings = Arrays.asList("Techndeck", "is", "awesome"); boolean anyMatchingWord = listOfStrings.stream().anyMatch(x -> x.equals("Techndeck")); System.out.println("List: "+listOfStrings.toString()); System.out.println("Is any string value from the list matching the desired word: "+anyMatchingWord); } } |
Output:
1 2 | List: [Techndeck, is, awesome] Is any string value from the list matching the desired word: true |
Note that both allMatch
and anyMatch
return a boolean value indicating whether or not the predicate is true for all or any elements in the stream, respectively. They short-circuit and stop processing the stream as soon as they find the first element that matches (in the case of anyMatch
) or the first element that does not match (in the case of allMatch
).
Filter/Remove null values from a List using Stream in Java 8...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams
filter null values from stream
Useful References: