java 8中 sorted分类排序

本文介绍了如何在Java8中使用Stream API和Comparator进行多条件排序,例如先按channelWeight降序,再按score降序。通过示例展示了sorted方法的使用,包括reversed()的作用。同时还提醒了如果对两个比较器都使用reversed()会产生的有趣现象,鼓励读者自行探索。

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

java 8中 sorted分类排序

1.需求: 先按照 channelWeight 进行 降序排列,如果 channelWeight 相同 再按照 score进行降序排列。
下面是实体:

@Data
class P {
    Double channelWeight;
    Double score;
    String channelName;
}

普通的sorted的用法就是:

		List<P> list = new ArrayList<>();
        P productItem1 = new P();
        productItem1.setChannelWeight(0.1D);
        productItem1.setChannelName("1");
        productItem1.setScore(0.9D);
        P productItem2 = new P();
        productItem2.setChannelWeight(0.1D);
        productItem2.setChannelName("1");
        productItem2.setScore(0.8D);
        P productItem3 = new P();
        productItem3.setChannelWeight(0.2D);
        productItem3.setChannelName("2");
        productItem3.setScore(0.7D);
        P productItem4 = new P();
        productItem4.setChannelWeight(0.2D);
        productItem4.setChannelName("2");
        productItem4.setScore(0.6D);
        list.add(productItem1);
        list.add(productItem2);
        list.add(productItem3);
        list.add(productItem4);
        //仅仅按照 ChannelWeight 进行倒排。
        list.stream().sorted(Comparator.comparingDouble(P::getChannelWeight).reversed()).collect(Collectors.toList());

reversed()作用:有它就是从大到小排列,没有就是从小到大排列

2.实现我们 1 的需求:

List<P> listAfterSortedByCwThenSc = list.stream().sorted(Comparator.comparingDouble(P::getChannelWeight).thenComparingDouble(P::getScore).reversed())
                .collect(Collectors.toList());

仅仅在 getScore 后面增加一个 reversed()方法就行。
在这里插入图片描述
⚠️注意:如果在 getChannelWeight 增加 reversed()方法同时 也在 getScore 增加 reversed()的话会发生有趣的现象,你们可以去试一下。 (狗头)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值