Comparator.comparing()
时间: 2023-10-14 21:25:57 浏览: 77
Comparator.comparing() is a method in Java that returns a Comparator object which compares the specified key extracted from the objects being compared. It is a convenient way to create a comparator for a class that has a natural ordering, or for a class that does not implement Comparable.
The method takes a Function as its argument, which is used to extract the key from the objects being compared. The returned Comparator compares the keys using their natural order, or using a Comparator that is passed as a second argument.
For example, to compare a list of Person objects by their age, we could use the following code:
```
List<Person> people = // list of Person objects
Comparator<Person> byAge = Comparator.comparing(Person::getAge);
Collections.sort(people, byAge);
```
This code creates a Comparator that compares Person objects by their age field, and then sorts the list of people using that comparator.
阅读全文