Home  >  Article  >  Java  >  What is the role of Comparators in Java?

What is the role of Comparators in Java?

WBOY
WBOYforward
2023-04-22 16:07:08993browse

Explanation

1. Comparator is a commonly used interface in old versions of Java. Java8 has added many default methods to this interface.

2. Comparator is an interface in javase, located under the java.util package. This interface is very abstract, and you need to master its usage.

In most cases, comparator is used for sorting, but sorting is one of the functions that comparator can achieve, and it is not limited to sorting.

Example

Comparator<Person> comparator = (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

The above is the detailed content of What is the role of Comparators in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete