对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(",");
持续更新......