1. Description
Java provides the comparison interface Comparable for comparison. All classes that implement this interface dynamically implement this comparison method. In fact, Java not only provides a comparison interface, but also provides another interface. The Comparator interface also has a comparison function, but this interface focuses on comparing containers.
2. Example
Comparator was widely used before Java8. Java8 not only upgrades to functional interfaces, but also extends default methods.
Comparatorcomparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0
Java is an object-oriented programming language that can write desktop applications, Web applications, distributed systems and embedded system applications.
The above is the detailed content of How to use Comparator in java. For more information, please follow other related articles on the PHP Chinese website!