java8 用strem流处理集合的例子 list转Set、Map

 

一. 需求:遍历List集合,集合中的对象的某个字段是以 逗号分割的,把分割后的值保存在Set集合中

普通的写法:

        Set cfgPortfolioSet = new HashSet<>(20);
        for (CfgPortfolio cfgPortfolio : cfgPortfolioList) {
            String compreftmp = cfgPortfolio.getComprefs();
            if(!StringTools.isTrimEmpty(compreftmp)){
                String[] split = compreftmp.split(",");
                for (String s : split) {
                    cfgPortfolioSet.add(s);
                }
             
            }
        }

java 8 stream流的写法:

一行代码搞定

Set  cfgPortfolioSet = cfgPortfolioList.stream().flatMap(cfgPortfolio -> {
            if (StringTools.isTrimEmpty(cfgPortfolio.getComprefs())) {
                return null;
            }
            return Arrays.stream(cfgPortfolio.getComprefs().split(","));
        }).collect(Collectors.toSet());

二. 将list集合转Set

普通list的转集合 是for语句遍历list,stream流直接一句代码

        // list 转 Set
        List manList = new ArrayList<>();
        Man man = new Man();
        man.setId("1");
        man.setName("人");
        manList.add(man);

        Set manSet =  manList.stream().collect(Collectors.toSet());
        manSet.contains("1");
        Iterator iterable =  manSet.iterator();
        while (iterable.hasNext()){
            System.out.println(iterable.next().getId());
        }

 

 

三. 将list集合转Map


        List manList = new ArrayList<>();
        manList.add(new Man("1", "人"));
        manList.add(new Man("1", "我"));

        //list to map 无重复key的时候
       // Map map1 = manList.stream().collect(Collectors.toMap(Man::getId, test->test));
        //System.out.println(map1.get("1").getName());

        //list to map 有重复key的时候
        Map map = manList.stream().collect(Collectors.toMap(Man::getId, Function.identity(),(test1, test2) -> test1 ));
        System.out.println(map.get("1").getName());

        //list to map value值取单个字段时
        Map mapname1 = manList.stream().collect(Collectors.toMap(Man::getId, Man::getName, (man1,man2)-> man1 ));
        System.out.println(mapname1.get("1"));

        //list to map value值拼接
        Map mapcomb = manList.stream().collect(Collectors.toMap(Man::getId, Man::getName, (key1, key2)-> key1+","+key2));
        System.out.println(mapcomb.get("1"));

        // list转map, 重复时将重复key的数据组成集合
        Map> maplist = manList.stream().collect(Collectors.toMap(Man::getId, p ->{
            List list = new ArrayList<>();
            list.add(p.getName());
            return list;
        }, (List value1, List value2 )-> {value1.addAll(value2); return  value1;}));
        System.out.println(maplist.get("1").toString());

 

 

你可能感兴趣的:(javaSe)