import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
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;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 根据年龄字段排序
Collections.sort(people, Comparator.comparingInt(Person::getAge));
// 打印排序后的列表
for (Person person : people) {
System.out.println(person);
}
}
}
Person
类:包含两个字段 name
和 age
,并提供相应的 getter 方法。List<Person>
列表:初始化一个包含多个 Person
对象的列表。Collections.sort
和 Comparator.comparingInt
排序:根据 Person
对象的 age
字段进行排序。Comparator.comparingInt
是 Java 8 引入的简化写法,可以更简洁地实现基于某个字段的排序。Person
对象的信息。这样就可以根据 age
字段对 List<Person>
进行排序了。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站