总结下自己使用过的特性

  • 将对象集合根据某个字段分组
//根据id分组
Map<String, List<Bean>> newMap = successCf.stream().collect(Collectors.groupingBy(b -> b.getId().trim()));
  • 获取对象集合里面的某个字段的集合
List<Bean> list = new ArrayList<>(); 
List<String> strList = list.stream().map(Bean::getId).collect(Collectors.toList());
  • 將集合字段转换成字符串
List<Long> longList = new ArrayList<>();
String s = longList.stream().map(Object :: toString).collect(Collectors.joining(","));
  • 提取字段去重distinct
List<String> strList = list.stream().map(Bean::getId).distinct().collect(Collectors.toList());
  • 提取字段去重set
Set<String> idSet = list.stream().map(Bean :: getId).collect(Collectors.toSet());
  • 过滤filter
Map<String, Integer> map = new HashMap<>();
//先分组
Map<String, List<Bean>> maps = list.stream().collect(Collectors.groupingBy(Bean::getname));
//循环获取到大小
houseIdMaps.forEach((s, names) -> {
            //房屋地址对应的条数
            map.put(s, names.size());
});
//过滤
//过滤重复的数据 >1
Map<String, Integer> mapRepeat = map.entrySet().stream().filter(entry -> entry.getValue() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
//过滤未重复的数据 =1
Map<String, Integer> mapNoRepeat = map.entrySet().stream().filter(entry -> entry.getValue() == 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  • 过滤filter,equals
List<Bean> list1 = list.stream().filter(a -> a.getId().equals("1")).collect(Collectors.toList());
  • 差集(基于java8新特性) 适用于大数据量
    /**
     * 差集(基于java8新特性) 适用于大数据量
     * 求List1中有的但是List2中没有的元素
     */
    public static List<String> subList(List<String> list1, List<String> list2) {
        Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
        return list1.parallelStream().filter(str-> !tempMap.containsKey(str)).collect(Collectors.toList());
    }
  • 交集(基于java8新特性) 适用于大数据量
    /**
     * 交集(基于java8新特性) 适用于大数据量
     * 求List1和List2中都有的元素
     */
    public static List<String> intersectList(List<String> list1, List<String> list2){
        Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
        return list1.parallelStream().filter(str-> tempMap.containsKey(str)).collect(Collectors.toList());
    }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部