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

应用场景(一):

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

示例:

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

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

mapList.add(mapStr3);



ArrayList> cs = mapList.stream()

.collect(Collectors

.collectingAndThen(Collectors

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

@Override    //重写比较器
public int compare(Map o1, Map 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的指定属性的去重,比如唯一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 persons = Arrays.asList(u1, u2, u3, u4);



List unique = persons.stream()

                    .collect(Collectors

                    .collectingAndThen(Collectors

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

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

                //循环取出结果

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

 

你可能感兴趣的:(java8-stream)