实现排序的几种方式/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);
结果:和之前list集合中的顺序一样

List<Person> collect = personList.stream()
.sorted((o1, o2) -> -1).collect(Collectors.toList());
System.out.println(collect);
结果:list集合中的顺序已经调换

我们直接直观的输出o1,o2,看给我们打印什么
List<Person> collect = personList.stream()
.sorted((o1, o2) ->{
System.out.println(o1);
System.out.println(o2);
return 1;
}).collect(Collectors.toList());
输出结果:

可以发现原先list集合中有5条数据,但我们输出o1,o2两两比较输出了8条数据。但是我们可以发现按照顺序,list集合中第一条数据和第二条数据开始进行比较时,我们在sort排序中输出的第一条数据o1却是却是我们进行比较的第二条数据。所以sorted中的o1相对来讲是二者比较的第二条数据,o2为二者比较的第一条数据 。
想要了解更多编程小知识,快来关注公众号:爪哇开发吧!每周会不定时的进行更新。



浙公网安备 33010602011771号