Java Reference
In-Depth Information
reverse ordering of a given comparator. So you can simply modify the previous example to sort
the apples by decreasing weight by reusing the initial Comparator:
Chaining Comparators
This is all nice, but what if you find two apples that have the same weight? Which apple should
have priority in the sorted list? You may want to provide a second Comparator to further refine
the comparison. For example, after two apples are compared based on their weight, you may
want to sort them by country of origin. The thenComparing method allows you to do just that. It
takes a function as parameter (just like the method comparing) and provides a second
Comparator if two objects are considered equal using the initial Comparator. You can solve the
problem elegantly again:
3.8.2. Composing Predicates
The Predicate interface includes three methods that let you reuse an existing Predicate to create
more complicated ones: negate, and, and or. For example, you can use the method negate to
return the negation of a Predicate, such as an apple that is not red:
You may want to combine two lambdas to say that an apple is both red and heavy with the and
method:
You can combine the resulting predicate one step further to express apples that are red and
heavy (above 150 g) or just green apples:
 
Search WWH ::




Custom Search