NimChimpsky
NimChimpsky

Reputation: 47290

Converting a Map<Integer, Object> to Map<Integer, List<Object>>, without using for loops (java)

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!

Upvotes: 0

Views: 1462

Answers (2)

ide
ide

Reputation: 20808

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.

Upvotes: 3

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

Upvotes: 0

Related Questions