原文链接:实现排序的几种方式/sorted(o1,o2) – 编程屋
1 实现排序的几种方式
首先我们先看代码
List<Person> personList = new ArrayList<>();
personList.add(new Person("王一",1));
personList.add(new Person("王二",2));
personList.add(new Person("王五",5));
personList.add(new Person("王三",3));
personList.add(new Person("王四",4));
对于这样的一组集合数据我们有很多种排序方法,今天我们就围绕它来展开讲述。
1.1 用lambda表达式直接进行排序
输出结果:
1.2 利用Collections直接进行倒序排序
Collections.sort(personList, (o1, o2) -> o2.getAge() - o1.getAge());
1.3 利用Java8中stream流进行排序
倒序方式1:
List<Person> collect = personList.stream()
.sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
倒序方式2:
List<Person> reverse = personList.stream()
.sorted(Comparator.comparing(Person::getAge, Comparator.reverseOrder())).collect(Collectors.toList());
System.out.println("倒序"+reverse);
正序方式1:
List<Person> sequence = personList.stream()
.sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
System.out.println("正序:"+sequence);
//正序:[Person{name='王一', age=1}, Person{name='王二', age=2}, Person{name='王三', age=3}, Person{name='王四', age=4}, Person{name='王五', age=5}]
2 stream流sorted排序中o1,o2分别代表什么
首先需要知道当两个元素比较时,返回一个正数,两个元素的位置不变。若返回一个负数的,则两个元素就调换位置
List<Person> collect = personList.stream()
.sorted((o1, o2) -> 1).collect(Collectors.toList());
System.out.println(collect);
以上只是部分内容,为了维护方便,本文已迁移到新地址:实现排序的几种方式/sorted(o1,o2) – 编程屋