As the title says, I am currently implementing the below code (well about to), is their a better way – as this seems a bit nasty.
Map<Integer, List<Objects>> allObjectsMap = newHashMap(); //guava
for(int i=1:i<myVar:i++){
Map<Integer, Objects> eachObjectMap = getMyObjectMap(i);
for(Map.Entry<Integer, Object> entry:eachObjectMap.entrySet()){
List objectList = allObjectsMap.get(entry.getKey())
if(objectList == null){//will be null the first time
objectList = newArrayList();//guava
objectList.add(entry.getValue());
allObjectsMap.put(entry.getKey(),objectList);
}
else{
objectList.add(entry.getValue());
}
}
}
Thanks!
You may wish to check out Guava’s ListMultimap.
One downside of this approach is that the final result is of type
Map<K, Collection<V>>and notMap<K, List<V>>. However, the ListMultimap.asMap() Javadoc states:Therefore, some sequence of casts (e.g.,
(Map<Integer, List<Object>>) (Map<Integer, ?>)) would work.