Java8新特性Stream之list转map及问题(Duplicate key)解决,附实验结果

Java8新特性Stream之list转map及问题(Duplicate key)解决,附实验结果

 

Exception in thread "main" java.lang.IllegalStateException: Duplicate key ??*VO (??=AAAAA, ??**=1, **??=null, ??=null)
    at java.util.stream.Collectors.lambda$throwingMerger$113(Collectors.java:133)
    at java.util.stream.Collectors$$Lambda$3/398887205.apply(Unknown Source)
    at java.util.HashMap.merge(HashMap.java:1245)
    at java.util.stream.Collectors.lambda$toMap$171(Collectors.java:1320)
    at java.util.stream.Collectors$$Lambda$5/762218386.accept(Unknown Source)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.stream.DistinctOps$1$2.accept(DistinctOps.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at com.*********************.main(??Service.java:271)

 

Java8使用stream的List转map遇到 Key重复的问题,直接转map时,你的key必须唯一:

public static void main(String[] args) {
        List<ElectricBalanceGoods> ebGoodsList = new ArrayList<>();
        ElectricBalanceGoods e0 = new ElectricBalanceGoods();
        e0.setDeviceCgid("AAAAA");
        e0.setBalanceId("1");
        e0.setId("1");
        ElectricBalanceGoods e1 = new ElectricBalanceGoods();
        e1.setDeviceCgid("AAAAA");
        e1.setBalanceId("1");
        e1.setId("2");
        ebGoodsList.add(e0);
        ebGoodsList.add(e1);
​
        Map<String, ElectricBalanceGoods> deviceBalance2ElectricBalanceGoodsMap = ebGoodsList.stream().distinct().collect(Collectors.toMap(egb -> egb.getDeviceCgid() + egb.getBalanceId(), ebg -> ebg));
        System.out.println(deviceBalance2ElectricBalanceGoodsMap);
​
    }

 

这个会报错:java.lang.IllegalStateException: Duplicate key

 

 

 

 

对key去重

 

 

关键代码

Function这个接口, 返回一个需要使用的数据。

这里要的是第一个出现的

Function.identity(),(e1, e2) -> e1)

可以操作e1、e2

 

比如俩都要:

放到list或者拼接起来、

 

 

更多操作(对value的操作)可以参考下面这篇文章:

https://blog.csdn.net/qq_39629277/article/details/83012548?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页