
Java
Java 8 流中按属性排序
Java 8引入了流(Stream)的概念,使得对集合进行各种操作变得更加简洁和方便。流提供了一种新的方式来处理集合中的元素,包括过滤、映射、排序等操作。在Java 8中,我们可以使用流的排序功能来按属性对集合进行排序,这在处理大量数据时非常有用。使用流的排序功能在Java 8中,我们可以使用流的sorted()方法来对集合进行排序。sorted()方法接受一个Comparator参数,该参数用于指定排序的规则。我们可以通过实现Comparator接口来自定义排序规则,也可以使用Java 8提供的一些默认排序规则。按属性排序的案例假设我们有一个Person类,该类包含姓名和年龄两个属性。我们可以使用流的sorted()方法按姓名对Person集合进行排序,代码如下:Javapublic 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; }}List<Person> people = new ArrayList<>();people.add(new Person("Alice", 25));people.add(new Person("Bob", 30));people.add(new Person("Charlie", 20));List<Person> sortedPeople = people.stream() .sorted(Comparator.comparing(Person::getName)) .collect(Collectors.toList());System.out.println(sortedPeople);运行上述代码,我们可以看到按照姓名对Person集合进行了排序,输出结果为:[Alice, Bob, Charlie]除了按姓名排序,我们还可以按照其他属性对集合进行排序,比如按照年龄。我们只需要修改sorted()方法中的Comparator即可,代码如下:
JavaList<Person> sortedPeople = people.stream() .sorted(Comparator.comparing(Person::getAge)) .collect(Collectors.toList());System.out.println(sortedPeople);运行上述代码,我们可以看到按照年龄对Person集合进行了排序,输出结果为:
[Charlie, Alice, Bob]Java 8中的流提供了一种简洁和方便的方式来对集合进行各种操作,包括排序。通过使用流的sorted()方法,我们可以按属性对集合进行排序。无论是按姓名、年龄还是其他属性,都可以通过修改Comparator来实现。这种方式不仅简化了代码,还提高了代码的可读性和可维护性。参考代码
Javaimport Java.util.ArrayList;import Java.util.Comparator;import Java.util.List;import Java.util.stream.Collectors;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 class MAIn { public static void mAIn(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); List<Person> sortedPeople = people.stream() .sorted(Comparator.comparing(Person::getName)) .collect(Collectors.toList()); System.out.println(sortedPeople); sortedPeople = people.stream() .sorted(Comparator.comparing(Person::getAge)) .collect(Collectors.toList()); System.out.println(sortedPeople); }}Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号