实现排序的几种方式/sorted(o1,o2)

本文介绍了在Java中对List集合进行排序的三种方法:使用Lambda表达式、Collections.sort()以及Java 8的Stream流。通过示例展示了如何根据Person对象的年龄属性进行升序和降序排序,并解释了排序过程中o1和o2代表的含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:实现排序的几种方式/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) – 编程屋

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值