import java.util.ArrayList;
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));
// 按照年龄排序
people.sort(Comparator.comparingInt(Person::getAge));
// 输出排序后的结果
people.forEach(System.out::println);
}
}
Person
:包含两个属性 name
和 age
,并提供了构造函数、getter方法和toString
方法。List<Person>
:使用 ArrayList
创建一个 Person
对象的列表,并添加几个 Person
实例。people.sort()
方法对列表进行排序,传入 Comparator.comparingInt(Person::getAge)
作为比较器,表示根据 age
属性进行排序。forEach
遍历排序后的列表,并打印每个 Person
对象的信息。这段代码展示了如何根据 List
中对象的某个属性(如 age
)进行排序。
上一篇:java 基本数据类型
下一篇:boolean在java中的含义
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站