Java list order by property
时间: 2024-05-03 20:23:19 浏览: 7
In Java, you can use the `Collections.sort()` method to order a list by a specific property. Here is an example:
Assuming you have a class `Person` with two properties `name` and `age`.
```
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
To sort a list of `Person` objects by their age property, you can use the following code:
```
List<Person> people = new ArrayList<>();
people.add(new Person("John", 25));
people.add(new Person("Jane", 20));
people.add(new Person("Bob", 30));
Collections.sort(people, Comparator.comparingInt(Person::getAge));
```
This will sort the `people` list in ascending order based on their age property. If you want to sort in descending order, you can use the `reversed()` method:
```
Collections.sort(people, Comparator.comparingInt(Person::getAge).reversed());
```