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 ObjectSortingExample {
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("\n按名字排序后的列表:");
for (Person person : people) {
System.out.println(person);
}
}
}
定义 Person 类:
name 和 age。toString 方法,以便于对象的创建和打印。创建 Person 对象列表:
ArrayList 创建一个 Person 对象的列表,并添加几个示例对象。按年龄排序:
Collections.sort 方法和自定义的 Comparator 来按年龄对 Person 对象进行排序。Comparator 的 compare 方法通过比较两个 Person 对象的 age 属性来决定排序顺序。按名字排序:
List 的 sort 方法和 Comparator.comparing 方法按名字对 Person 对象进行排序。Comparator.comparing 是 Java 8 引入的一个简化方法,可以直接传递属性的 getter 方法。打印排序结果:
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站