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:

 

/**
 * 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:

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”:

 

/**
 * 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:

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...!!! Share on X

Do you like this Post? – then check my other helpful posts:

 filter null values from stream

Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts