views:

65

answers:

2

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!

A: 

Can't you just cast it? Java erases all type information in the generated code, so it should be enough.

Thorbjørn Ravn Andersen
He doesn't state anywhere that the object in his map are, in fact, lists. Casting it would just yield a ClassCastException when he retrieves an item from his map.
Joeri Hendrickx
+3  A: 

You may wish to check out Guava's ListMultimap.

Multimap<Integer, Object> multimap = ArrayListMultimap.create();
for (int i = 0; i < myVar; i++) {
  multimap.putAll(Multimaps.forMap(getMyObjectMap(i)));
}
Map<Integer, Collection<Object>> allObjectsMap = multimap.asMap();

One downside of this approach is that the final result is of type Map<K, Collection<V>> and not Map<K, List<V>>. However, the ListMultimap.asMap() Javadoc states:

Though the method signature doesn't say so explicitly, the returned map has List values.

Therefore, some sequence of casts (e.g., (Map<Integer, List<Object>>) (Map<Integer, ?>)) would work.

ide
I don't think you need generic information on ArrayListMultimap.<Integer, Object>create(), a simpler solution would be ArrayListMultimap.create()
nanda