stream流排序、分组(list<实体类>、list<map>)

  1. 实体类排序
    排序方法:sorted()
// 业务获取当前list
List<SellVo> records = data.getRecords();

List<SellVo> collect1 = records.stream().sorted(Comparator.comparing(SellVo::getSellAmount()).reversed()).collect(Collectors.toList());
//或: Comparator.comparing( (SellVo x) -> x.getSellAmount() ).reversed()

  1. map排序
List<Map<String,Object>> records = data.getRecords();

// 在Comparator.comparing方法中x默认为Object,需要x指向为Map类(实体类也是一样的,可以使用该方法)
// 需要注意排序方式默认为正序,大部分情况下需要倒叙reversed
// 排序的时候需要注意,string类型和int类型排序方式是不同的,int优先数字大小,string优先长度
List<Map> sellAmount = hashMaps.stream().sorted(Comparator.comparing((Map x) -> (Integer) x.get("sellAmount")).reversed()).collect(Collectors.toList());
  1. 单条件分组
    分组方法Collectors.groupingBy()
List<ShopCarVo> records =  = data.getRecords();

Map<Object, List<ShopCarVo>> collect = records.stream().map(x -> {
            // 业务处理
            return x;
        }).collect(Collectors.groupingBy(o -> o.getSiteId(), Collectors.toList()));
  1. 多条件分组
List<ShopCarVo> records =  = data.getRecords();

Map<Object, List<ShopCarVo>> collect = records.stream().map(x -> {
            // 业务处理
            return x;
            //分组的业务就相当于 创建一个键,该键是分组的条件,满足该键的放在一个map中
			// 分组条件为SiteId与BusinessId两个条件 组成map的key值
        }).collect(Collectors.groupingBy(o -> o.getSiteId() + "_" + o.getBusinessId(), Collectors.toList()));
  1. map转成list;
// map转换成list
        List<List<ShopCarVo>> collect = collect.values().stream().collect(Collectors.toList());

//另外补一个不相关的,map的stream流可以遍历values、keySet; collect.keySet().stream()...
  1. map根据主键排序
LinkedHashMap<String, List<UserRps>> collect1 = collect.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (old, now) -> old, LinkedHashMap::new));

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vace cc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值