Java8 对集合进行排序

本文详细介绍了如何使用 Java 的 Stream API 对集合中的对象进行排序,包括根据对象属性的正序和逆序排序,以及如何针对不同类型的属性(如 Integer 和 String)实现排序。通过具体示例,读者可以学习到利用 Lambda 表达式和方法引用进行高效的数据处理。

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

0.根据集合的对象或属性 正序排序

    0.1根据属性

List<Goods> collect = goodsList.stream().sorted(Comparator.comparing(Goods::getAmunt)).collect(Collectors.toList());

    0.2根据对象本身,适应于(List<Integer> 或 List<String>)

List<String> collect = list.stream().sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList());

1.根据集合的对象的属性(Integer)进行排序

    1.1正序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> Integer.compare(x.getAmunt(),y.getAmunt()))
                      .collect(Collectors.toList());

    1.2逆序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> Integer.compare(y.getAmunt(),x.getAmunt()))
                      .collect(Collectors.toList());

2.根据集合的对象的属性(String)进行排序

    2.1正序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> x.getName().compareTo(y.getName()))
                      .collect(Collectors.toList());

    2.2 逆序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> y.getName().compareto(x.getName()))
                      .collect(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值