你能帮我解决
Java Streams吗?
正如您从标题中看到的,我需要合并List< Map< String,Map< String,Genuineness>>>到Map< String,Genuineness>>.
该列表表示为List< Map< String,Genuineness>>>看起来像:
[ { "USER_1":{ "APP_1":{ "total":1,"totalGenuine":1,"totalDevelopment":1 } },"USER_2":{ "APP_1":{ "total":1,"totalDevelopment":1 },"APP_2":{ "total":2,"totalGenuine":2,"totalDevelopment":2 } } },{ "USER_1":{ "APP_1":{ "total":1,"totalDevelopment":2 } } } ]
因此,正如您所看到的,重复的键可能无处不在.
我的目标是将它们组合成Map< String,Genuineness>>通过合并真实性.合并真实性仅仅意味着返回一个新的对象,其总和值为total,totalGenuine和totalDevelopment.
这是我的实现失败:
final Map<String,Map<String,Genuineness>> map = taskHandles.stream().map(this::mapTaskHandle) .flatMap(m -> m.entrySet().stream()).collect( Collectors.toMap(Map.Entry::getKey,e -> e.getValue().entrySet().stream() .collect( Collectors.toMap(Map.Entry::getKey,g -> new Genuineness(g.getValue().getTotal(),g.getValue().getTotalGenuine(),g.getValue().getTotalDevelopment()),(g1,g2) -> new Genuineness(g1.getTotal() + g2.getTotal(),g1.getTotalGenuine() + g2.getTotalGenuine(),g1.getTotalDevelopment() + g2.getTotalGenuine() ) ) ) ) );
它失败并带有消息:
java.lang.IllegalStateException: Duplicate key {TEST_33_33_APP_1=live.attach.billing.domain.model.billing.Genuineness@951b6fe}
所以,似乎在我的实现中我已经指出了如何组合内部地图但没有合并外部地图的值,我不知道该怎么做.
我非常感谢你的帮助.先感谢您!
更新:
预期产量:
{ "USER_1":{ "APP_1":{ "total":2,"totalDevelopment":2 } },"USER_2":{ "APP_1":{ "total":2,"totalDevelopment":2 },"APP_2":{ "total":4,"totalGenuine":4,"totalDevelopment":4 } } }
解决方法
老实说,这是一个可怕的数据结构,这段代码的维护者很难找到出现的问题.
你应该退一步考虑重构代码,你可以通过在最外面的toMap中使用以下合并函数来解决缺失的部分:
(l,r) -> { r.forEach((k,v) -> l.merge(k,v,(bi,bii) -> new Genuineness(bi.getTotal() + bii.getTotal(),bi.getTotalGenuine() + bii.getTotalGenuine(),bi.getTotalDevelopment() + bii.getTotalGenuine()))); return l; }
完整代码:
taskHandles.stream().map(this::mapTaskHandle) .flatMap(m -> m.entrySet().stream()).collect( Collectors.toMap(Map.Entry::getKey,g1.getTotalDevelopment() + g2.getTotalGenuine() ) ) ),(l,r) -> { r.forEach((k,bi.getTotalDevelopment() + bii.getTotalGenuine()))); return l; } ) );