Java8--stream流操作对List、List的过滤处理经验分享

应用场景(一):

    1.对list<map>中map中某个指定的key的value的去重,得到新的list:去除了重复出现指定key的value值得map

示例:

                要求:过滤掉电话相同的map

                List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
Map<String, Object> mapStr1 = new HashMap<String, Object>();
mapStr1.put(“name”, “丽丽”);
mapStr1.put(“sex”, “女”);
mapStr1.put(“age”, 22);
mapStr1.put(“tel”, “110”);
Map<String, Object> mapStr2 = new HashMap<String, Object>();
mapStr2.put(“name”, “丽丽”);
mapStr2.put(“sex”, “女”);
mapStr2.put(“age”, 23);
mapStr2.put(“tel”, “120”);
Map<String, Object> mapStr3 = new HashMap<String, Object>();
mapStr3.put(“name”, “丽丽”);
mapStr3.put(“sex”, “女”);
mapStr3.put(“age”, 24);
mapStr3.put(“tel”, “110”);
mapList.add(mapStr1);
mapList.add(mapStr2);

mapList.add(mapStr3);

ArrayList<Map<String, Object>> cs = mapList.stream()

.collect(Collectors

.collectingAndThen(Collectors

.toCollection(() -> new TreeSet<>(new Comparator<Map<String, Object>>() {

@Override    //重写比较器

public int compare(Map<String, Object> o1, Map<String, Object> o2) {

if (o1.get(“tel”).equals(o2.get(“tel”))) {

return 0;

}

return 1;

}

})), ArrayList::new));

               //循环取出结果

cs.forEach(m -> {

System.out.println(“======map========”);

m.keySet().forEach(n -> System.out.println(n + “–>” + m.get(n)));

});

应用场景(二):

    对list<T>中对象T的指定属性的去重,比如唯一ID,tel,获取新的list:去除了重复出现的指定属性值的对象T

示例:

    要求过滤掉电话相同的user

                User u1 = new User(1, “小米1”, “001号”, “女”, 21, “110”);
User u2 = new User(2, “小米2”, “002号”, “男”, 11, “120”);
User u3 = new User(3, “小米3”, “003号”, “女”, 21, “119”);
User u4 = new User(4, “小米4”, “004号”, “女”, 34, “110”);

List<User> persons = Arrays.asList(u1, u2, u3, u4);

List<User> unique = persons.stream()

                    .collect(Collectors

                    .collectingAndThen(Collectors

                    .toCollection(() -> new TreeSet<>(Comparator

                    .comparing(User::getTel))), ArrayList::new));

                //循环取出结果

unique.forEach(p -> System.out.println(p.toString()));

    原文作者:一场秋
    原文地址: https://blog.csdn.net/qq_33110175/article/details/80705842
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞