Comparator: Difference between revisions
Jump to navigation
Jump to search
Line 38: | Line 38: | ||
apples.sort(Comparator.comparing(Apple::getWeight)); | apples.sort(Comparator.comparing(Apple::getWeight)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Comparator.comparing()= | |||
Factory methods that produces comparator lambdas, based on various criteria. | |||
=Composition Methods= | =Composition Methods= |
Revision as of 19:35, 29 March 2018
External
Internal
Overview
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
...
}
Concise Sorting
Java 8 List has a sort() method that accepts a java.util.Comparator.
java.util.Comparator is a functional interface, so we can provide a lambda expression instead.
java.util.Comparator comes with static methods that build Comparator instances, so if compare apples by weight, we can write this:
List<Apple> apples = ...
apples.sort(Comparator.comparing(a -> a.getWeight()));
The last form can be compacted even further using method references:
List<Apple> apples = ...
apples.sort(Comparator.comparing(Apple::getWeight));
Comparator.comparing()
Factory methods that produces comparator lambdas, based on various criteria.