Java list order by property
时间: 2024-05-06 16:20:34 浏览: 9
To sort a list of objects by a specific property, you can use the `Comparator` interface in Java. Here's an example:
Assuming you have a class `Person` with properties `name`, `age`, and `salary`, you can sort a list of `Person` objects by their salary in ascending order like this:
```
List<Person> people = new ArrayList<>();
// add some people to the list...
// sort by salary in ascending order
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getSalary(), p2.getSalary());
}
});
```
This code uses the `Collections.sort` method to sort the `people` list. The second argument to `sort` is a `Comparator` object that compares two `Person` objects based on their salary. The `compare` method returns a negative value if `p1`'s salary is less than `p2`'s salary, a positive value if `p1`'s salary is greater than `p2`'s salary, and 0 if their salaries are equal.
You can also sort by other properties by changing the `compare` method to compare the desired properties.