在Java中,你可以使用sorted()函数与Comparator结合实现多级排序
import java.util.*; class Person { String name; int age; double salary; public Person(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } } public class MultiLevelSortingExample { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 30, 1200.0), new Person("Bob", 25, 1000.0), new Person("Charlie", 30, 1100.0), new Person("David", 28, 900.0) ); // 按年龄升序排序,如果年龄相同则按薪水升序排序 Comparator<Person> comparator = Comparator.comparingInt((Person p) -> p.age) .thenComparingDouble(p -> p.salary); List<Person> sortedPeople = people.stream() .sorted(comparator) .collect(Collectors.toList()); System.out.println("Multi-level sorted list:"); for (Person person : sortedPeople) { System.out.println(person); } } }在这个示例中,我们首先创建了一个Person类,并定义了一些属性。然后,我们创建了一个包含Person对象的列表,并使用Stream API 和 sorted() 函数对其进行多级排序。
我们创建了一个Comparator,首先根据年龄进行升序排序,然后根据薪水进行升序排序。最后,我们将排序后的结果收集到一个新的列表中,并打印出来。
本文由作者笔名:VPS评测 于 2025-06-01 23:28:33发表在本站,原创文章,禁止转载,文章内容仅供娱乐参考,不能盲信。
本文链接: https://www.vpsvpsvps.com/wen/133132.html