Java Reference
In-Depth Information
.flatMap(i ->
numbers2.stream()
.filter(j -> (i + j) % 3 == 0)
.map(j -> new int[]{i, j})
)
.collect(toList());
The result is [(2, 4), (3, 3)].
5.3. Finding and matching
Another common data processing idiom is finding whether some elements in a set of data match
a given property. The Streams API provides such facilities through the allMatch, anyMatch,
noneMatch, findFirst, and findAny methods of a stream.
5.3.1. Checking to see if a predicate matches at least one element
The anyMatch method can be used to answer the question “Is there an element in the stream
matching the given predicate?” For example, you can use it to find out whether the menu has a
vegetarian option:
if(menu.stream().anyMatch(Dish::isVegetarian)){
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}
The anyMatch method returns a boolean and is therefore a terminal operation.
5.3.2. Checking to see if a predicate matches all elements
The allMatch method works similarly to anyMatch but will check to see if all the elements of the
stream match the given predicate. For example, you can use it to find out whether the menu is
healthy (that is, all dishes are below 1000 calories):
boolean isHealthy = menu.stream()
.allMatch(d -> d.getCalories() < 1000);
Search WWH ::




Custom Search