Java List 对象属性排序:Stream API 实战指南
使用 Java Stream API 对 List 对象按属性排序
在 Java 8 中,Stream API 为集合操作提供了强大的工具。您可以利用 Stream API 轻松地对 List 中的对象根据其属性进行排序。
关键步骤:
- 使用
stream()方法将 List 转换为 Stream。 - 使用
sorted()方法并结合Comparator接口指定排序属性。 - 使用
collect()方法将排序后的 Stream 转换回 List。
代码示例:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("John", 25));
personList.add(new Person("Alice", 30));
personList.add(new Person("Bob", 20));
// 使用 Stream API 按姓名排序
List<Person> sortedList = personList.stream()
.sorted(Comparator.comparing(Person::getName))
.collect(Collectors.toList());
// 打印排序后的结果
for (Person person : sortedList) {
System.out.println(person.getName() + " - " + person.getAge());
}
}
}
// Person 类
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;
}
}
输出结果:
Alice - 30
Bob - 20
John - 25
灵活排序
您可以通过修改 Comparator.comparing() 方法中的参数来指定不同的排序属性。例如,要按年龄排序,可以使用 Comparator.comparing(Person::getAge)。
总结
使用 Stream API 对 List 中的对象按属性排序非常方便。通过 sorted() 方法和 Comparator 接口,您可以灵活地控制排序方式,满足各种需求。
原文地址: http://www.cveoy.top/t/topic/eWS 著作权归作者所有。请勿转载和采集!