import java.util.*;
import java.util.stream.Collectors;
public class ComparatorExample {
public static void main(String[] args) {
// 创建一个包含多个Person对象的列表
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// 使用Comparator.comparing按照年龄对列表进行排序
List<Person> sortedByAge = people.stream()
.sorted(Comparator.comparing(Person::getAge))
.collect(Collectors.toList());
// 输出排序后的结果
sortedByAge.forEach(person -> System.out.println(person.getName() + " - " + person.getAge()));
}
}
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;
}
}
Person
类,包含两个属性:name
和age
,并提供了构造方法、getter方法。Person
对象的列表people
。Comparator.comparing
方法,根据Person
对象的age
属性对列表进行排序。这里使用了方法引用Person::getAge
来指定比较的属性。Person
对象的姓名和年龄。这个示例展示了如何使用Comparator.comparing
方法对对象列表进行排序。
上一篇:java wrapper
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站