美文网首页
java8 Lambda Stream操作list,map

java8 Lambda Stream操作list,map

作者: 请叫我蔡蔡先生 | 来源:发表于2020-01-09 10:12 被阅读0次

    1.对多个属性去重

    List newList = list.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                            o ->    o.getProductName() + ";" +
                                    o.getManufactureName() +";"+
                                    o.getShopSign() +";"+
                                    o.getSpecComment() +";"+
                                    o.getProductTypeCode() +";"+
                                    o.getWeight() +";"+
                                    o.getWarehouseCode() +";"+
                                    o.getPackCode()
                            ))
                    ), ArrayList::new));
    

    2.分组

    //根据多个属性分组
    Map<String, List<String>> groupBy = voList.stream().collect(Collectors.groupingBy(CountDefaultOrderVo::getProviderCode,
                        Collectors.mapping(CountDefaultOrderVo::getPackCode, Collectors.toList())));
    //根据某一个属性分组                 
    Map<Integer, List<TestStreamModel>> map = list.stream().collect(Collectors.groupingBy(t -> t.getGrade()));  
    

    3.过滤

    List list = new ArrayList();
    list.add("1");
    List collect = list.stream().filter(x -> {
        if (!("0.5".equals(x) || "1".equals(x))) {
            return true;
        }
        return false;
    }).collect(Collectors.toList());
    

    4.list转map

    Map result1 = list.stream().collect(Collectors.toMap(对象::属性1, 对象::属性2));
    

    5.map转list

    map.entrySet().stream().map(e -> new Person(e.getKey(),e.getValue())).collect(Collectors.toList());
    

    6.遍历map

    map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
    

    相关文章

      网友评论

          本文标题:java8 Lambda Stream操作list,map

          本文链接:https://www.haomeiwen.com/subject/wrfyactx.html