Java 8 Stream – allMatch, anyMatch, noneMatch
Stream API provides facilities to check weather elements in a certain set of data satisfy some conditions. This is done by allMatch, anyMatch, noneMatch
methods of stream.
anyMatch
anyMatch can be used to see if there is an element in the stream matching given Predicate and returns boolean. Let’s say we have a country and want to see if there is a city with population more than two million:
if (country.stream().anyMatch(city -> city.population() > 2000000)) {
System.out.println("There is a big city :)");
}
allMatch
allMatch is be used to apply a predicate over all the stream. Referring to the above example we can say check if population in each city is less than 3 million:
if (country.stream().allMatch(city -> city.population() < 4000000)) {
System.out.println("There is no really big city in country :)");
}
noneMatch
noneMatch is used to check if none of the stream data satisfied given predicate. For our example we can say none of the cities has population less than 200000:
if (country.stream().noneMatch(city -> city.population() < 200000)) {
System.out.println("There is no small city in country :)");
}