嗨,我在执行代码时遇到错误:
java.lang.IllegalStateException: Duplicate key ad.ecs.core.scriptengine.SiteIDAndNPI@3a75ce6f
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
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 ad.ecs.core.scriptengine.Utils.getInterfaceIDsWithSiteIDAndNPI(Utils.java:689)
我正在尝试将我的列表分组到地图中:
public static Map<Integer, SiteIDAndNPI> getInterfaceIDsWithSiteIDAndNPI(Session session) {
@SuppressWarnings("unchecked")
List<Srvsetup> srvsetups = session.createCriteria(Srvsetup.class)
.add(Restrictions.gt("scriptinterfaceid", 0))
.list();
Map<Integer, SiteIDAndNPI> interfaceIDs = srvsetups.stream()
.collect(Collectors.toMap(srv -> srv.getScriptinterfaceid(),
srv -> getSiteIDAndNPI(srv.getId().getSiteid(), session)));
@SuppressWarnings("unchecked")
List<Facsetup> facsetups = session.createCriteria(Facsetup.class)
.add(Restrictions.gt("scriptinterfaceid", 0))
.list();
interfaceIDs.putAll(facsetups.stream()
.collect(Collectors.toMap(fac -> fac.getScriptinterfaceid(),
fac -> getSiteIDAndNPI(fac.getPlid(), session))));
return interfaceIDs;
}
public static SiteIDAndNPI getSiteIDAndNPI(int siteID, Session session) {
SiteIDAndNPI siteIDAndNPI = new SiteIDAndNPI();
siteIDAndNPI.setSiteID(siteID);
Mdsetup1 mdsetup1 = (Mdsetup1) session.get(Mdsetup1.class, siteID);
if (mdsetup1 != null)
siteIDAndNPI.setNPI(mdsetup1.getProviderId());
return siteIDAndNPI;
}
我查看了这个链接:Java 8 List<V> into Map<K, V>
有建议使用group by。但我不想得到这样的地图:
Map<Integer, List<SiteIDAndNPI>>
相反,我想覆盖重复的键。如果不做一些丑陋的代码,它是否可以实现?
答案 0 :(得分:5)
不确定。只需使用接受合并功能的toMap
重载:
Collectors.toMap(fac -> fac.getScriptinterfaceid(),
fac -> getSiteIDAndNPI(fac.getPlid(), session, log),
(value1, value2) -> value2 /* accept the second version */))
答案 1 :(得分:0)
尝试使用
list.stream.collect(Collectors.groupingBy(srv::Scriptinterfaceid))
这将返回一个带有Scriptinterfaceid的地图作为Key&amp; List<srv>
作为价值。