Stream:常见使用场景

本文介绍了如何使用JavaStream对Map和List<Map>进行排序,包括正序和倒序,以及如何按多个属性去重。此外,还展示了如何合并多个集合和将List<Object>的某个属性转为逗号分隔的字符串。

对Stream流简单使用(单个集合、集合和集合),见Stream:常用示例

此篇博客是对上文未提到的,日常工作中常见的stream用法进行补充

    • 排序

1.1 对map排序

 //map根据value倒序排序
 map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
//map根据key倒序排序
 map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey()));
//map根据value正序排序
 map.entrySet().stream().sorted(Map.Entry.comparingByValue());
 map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue())).forEach(System.out::println);
//map根据key正序排序
 map.entrySet().stream().sorted(Map.Entry.comparingByKey());
 map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).forEach(System.out::println);

1.2 对List<Map>排序

//正序
List<Map<String,Object> result = list.stream().sorted((m1,m2)-> MapUtils.getIntValue(m1,"totalNum") - MapUtils.getIntValue(m2,"totalNum")).collect(Collectors.toList());
//或
List<Map<String, Object>> result = list.stream().sorted(Comparator.comparingInt(m -> MapUtils.getIntValue(m, "totalNum"))).collect(Collectors.toList());
//倒序
List<Map<String,Object> result = list.stream().sorted((m1,m2)-> MapUtils.getIntValue(m2,"totalNum") - MapUtils.getIntValue(m1,"totalNum")).collect(Collectors.toList());
//或
List<Map<String, Object>> result = list.stream().sorted(Collections.reverseOrder(Comparator.comparingInt(m -> MapUtils.getIntValue(m, "totalNum")))).collect(Collectors.toList());

注意:这里的排序后是重新生成新的集合

    • 去重

2.1 按多个属性(字段)去重

List<DeviceManage> collect = dataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new ConcurrentSkipListSet<>(Comparator.comparing(DeviceManage::getDeviceTypeCode).thenComparing(DeviceManage::getAffiliatedUnitId))), ArrayList::new));

注:

ConcurrentSkipListSet::线程安全

TreeSet::线程不安全

    • 集合合并

List<Integer> mergedList = Stream.of(list1, list2, list3).flatMap(Collection::stream).collect(Collectors.toList());

//List<Object>合并某个属性并转为逗号分隔的字符串
String opcCodes = dtoList.stream().filter(item -> CollectionUtils.isNotEmpty(item.getFactorSimpleDtoList())).map(PositionFactorsDto::getFactorSimpleDtoList)
        .flatMap(Collection::stream).filter(item2 -> StringUtils.isNotBlank(item2.getOpcCode())).map(FactorSimpleDto::getOpcCode)
        .collect(Collectors.joining(",");

持续更新......

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值