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 ListSortExample {
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, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
});
System.out.println("按年龄升序排序后的列表:");
for (Person person : people) {
System.out.println(person);
}
// 按姓名字母顺序排序
people.sort(Comparator.comparing(Person::getName));
System.out.println("按姓名字母顺序排序后的列表:");
for (Person person : people) {
System.out.println(person);
}
}
}
Person
类:包含两个属性 name
和 age
,并提供构造函数、getter 方法和 toString
方法。List<Person>
列表:使用 ArrayList
创建一个 Person
对象的列表,并添加一些示例数据。Collections.sort
方法和自定义的 Comparator
来根据 age
属性对列表进行排序。List.sort
方法和 Comparator.comparing
方法来根据 name
属性对列表进行排序。toString
方法打印排序后的结果。上一篇:java聊天室代码
下一篇:java 静态代码块
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站