案例一:
- Comparator多属性排序: 先按名字不分大小写排,再按GID倒序排,最后按年龄正序排
@AllArgsConstructor @Data public class Person { private String name; private String gid; private Integer age; }
import com.google.common.collect.Lists; import com.ultra.cmp.report.dto.Person; import java.util.Comparator; import java.util.List; /** * @author ygf * @date 2022/9/2 9:26 */ public class TestPer { public static void main(String[] args) { List<Person> personList = getTestList(); personList.sort(Comparator.comparing(Person::getName, String.CASE_INSENSITIVE_ORDER) .thenComparing(Person::getGid, (a, b) -> b.compareTo(a)) .thenComparingInt(Person::getAge)); personList.stream().forEach(System.out::println); } public static List<Person> getTestList() { return Lists.newArrayList(new Person("dai", "301", 10), new Person("dai", "303", 10), new Person("dai", "303", 8), new Person("dai", "303", 6), new Person("dai", "303", 11), new Person("dai", "302", 9), new Person("zhang", "302", 9), new Person("zhang", "301", 9), new Person("Li", "301", 8)); } }
输出结果:
Person(name=dai, gid=303, age=6) Person(name=dai, gid=303, age=8) Person(name=dai, gid=303, age=10) Person(name=dai, gid=303, age=11) Person(name=dai, gid=302, age=9) Person(name=dai, gid=301, age=10) Person(name=Li, gid=301, age=8) Person(name=zhang, gid=302, age=9) Person(name=zhang, gid=301, age=9)
对Stream中的元素进行排序:reversed():倒序
String[] array = { "c", "c", "a", "b", "b", "e", "e", "d", "d"}; List<String> newList = Arrays.stream(array).sorted().collect(Collectors.toList()); List<Student> students = new ArrayList<>(); students.add(new Student("Mike", 10, "male", 88)); students.add(new Student("Jack", 13,"male", 90)); students.add(new Student("Lucy", 15,"female", 100)); students.add(new Student("Jessie", 12,"female", 78)); students.add(new Student("Allon", 16,"female", 92)); students.add(new Student("Alis", 22,"female", 50)); //正序 List<String> nameList = students.stream() .sorted(Comparator.comparing(Student::getScore)) .map(Student::getName) .collect(Collectors.toList()); System.out.println("按成绩排序输出学生姓名:" + nameList); //倒序 List<String> nameList2 = students.stream() .sorted(Comparator.comparing(Student::getScore).reversed()) .map(Student::getName) .collect(Collectors.toList()); System.out.println("按成绩排序输出学生姓名:" + nameList2); //按成绩排序输出学生姓名:[Alis, Jessie, Mike, Jack, Allon, Lucy] //按成绩排序输出学生姓名:[Lucy, Allon, Jack, Mike, Jessie, Alis] 正序: list=list.stream().sorted().collect(Collectors.toList()); 或者 list.stream().sorted(Comparator.comparing(Student::getAge)) ; 倒序: list.stream().sorted(Comparator.comparing(Student::getAge)) ; list.stream().sorted(Comparator.comparing(Student::getAge).reversed()); //含空值的正序(升序)排序(按创建时间排序) nullsFirst:空值放第一位 list=list.stream().sorted(Comparator.comparing(l -> l.getCreateTime(), Comparator.nullsFirst(Date::compareTo))).collect(Collectors.toList()); //nullsLast:空值放最后 list=list.stream().sorted(Comparator.comparing(l -> l.getCreateTime(), Comparator.nullsLast(Date::compareTo).reversed())).collect(Collectors.toList());