在Java中,可以通过使用sorted()函数与Lambda表达式结合对集合进行排序
首先,确保已经导入了以下所需的类:
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors;接下来,创建一个简单的实体类,例如Person:
public 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; } public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }现在,创建一个Person对象的列表并使用sorted()函数对其进行排序。这里我们将使用两种不同的排序方法:按姓名排序和按年龄排序。
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)); // 按姓名排序(升序) List<Person> sortedByName = people.stream() .sorted((p1, p2) -> p1.getName().compareTo(p2.getName())) .collect(Collectors.toList()); System.out.println("Sorted by name: " + sortedByName); // 按年龄排序(升序) List<Person> sortedByAge = people.stream() .sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())) .collect(Collectors.toList()); System.out.println("Sorted by age: " + sortedByAge); } }运行上述代码,你将看到如下输出:
Sorted by name: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}] Sorted by age: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]在这个示例中,我们使用了Lambda表达式作为sorted()函数的参数,以便根据需要对Person对象列表进行排序。
本文由作者笔名:VPS评测 于 2025-06-01 23:28:29发表在本站,原创文章,禁止转载,文章内容仅供娱乐参考,不能盲信。
本文链接: https://www.vpsvpsvps.com/wen/133129.html