ThenComparingInt
时间: 2024-05-15 20:12:41 浏览: 9
`ThenComparingInt` is a method in Java that is used to sort a collection of objects based on a comparison of their integer properties. It is typically used in conjunction with the `Comparator` interface, which provides a way to define custom comparison functions for objects.
When sorting a collection of objects, it is often necessary to sort them based on multiple properties. For example, if we have a collection of `Person` objects, we might want to sort them first by their last name, and then by their age. This is where `ThenComparingInt` comes in handy.
Here's an example:
```
List<Person> people = new ArrayList<>();
people.add(new Person("John", "Doe", 25));
people.add(new Person("Jane", "Doe", 30));
people.add(new Person("Bob", "Smith", 20));
Comparator<Person> lastNameComparator = Comparator.comparing(Person::getLastName);
Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge);
people.sort(lastNameComparator.thenComparingInt(ageComparator));
```
In this example, we first define two comparators: one that compares people by last name, and another that compares people by age. We then use `thenComparingInt` to create a new comparator that first compares people by last name, and then by age. Finally, we sort the list of people using this composite comparator.
The result of this code would be a list of people sorted first by last name (in alphabetical order), and then by age (from youngest to oldest):
```
Bob Smith (20 years old)
Jane Doe (30 years old)
John Doe (25 years old)
```