Java8 Stream 使用技巧

Java8 Stream 使用技巧,第1张

  • 排序
list.stream()
            .sorted(Comparator.comparing(x -> MapUtils.getString((Map) x, "order"))   //排序字段
            .reversed())   //反转
            .collect(Collectors.toList());
  • List 分组
Map<String, List<Map<String, Object>>> groupList =
            list.stream().collect(Collectors.groupingBy(x -> MapUtils.getString(x, "code"))); //分组字段
  • List to Map
Map<String, OrganizationVo> orgMap =
                orgList.stream().
                collect(Collectors.toMap(OrganizationVo::getOrgId, Function.identity(), (a, b) -> a));
                // OrganizationVo::getOrgId 映射成 key
                // Function.identity() 即 e -> e 映射成 value
                // (a, b) -> a 是防止key重复的选择策略 
  • List 去重
// 普通简单写法
Set<Object> set = Sets.newConcurrentHashSet();
List<OrganizationVo> resultList = 
list.stream().filter(vo -> set.add(vo.getOrgId())).collect(Collectors.toList());
// 函数式接口写法
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Set<Object> set = Sets.newConcurrentHashSet();
    return t -> set.add(keyExtractor.apply(t));
}

List<OrganizationVo> resultList= 
list.stream().filter(distinctByKey(vo -> vo.getOrgId())).collect(Collectors.toList());

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/919418.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存