java - Iterating over List in a Map -
what best way iterate on "de-normalized" map of collections?
for example, have following map:
map<string, list<string>> relations; in order iterate on each key -> each value like:
for (entry<string,list<string>> e : relations.entries()) { (string s : e.getvalue()) { system.out.println(e.getkey() + " - " + s); } } is there elegant way solve decorator or so?
i'm hoping find like:
for(entry e : collections.getdenormalizeentriesfrommapofcollection(mymap)) { system.out.println(e.getkey() + " - " + e.getvalue()); } that give same result, on second situation have 1 entry each key -> collection item.
i recommend @ guavas multimap implementation. have kind of iterator:
to transform map<k, collection<v> multimap<k, v> can use utility method:
public static <k,v> multimap<k,v> tomultimap(map<k,? extends collection<v>> m) { linkedlistmultimap<k, v> multimap = linkedlistmultimap.create(); (entry<k, ? extends collection<v>> e : m.entryset()) multimap.putall(e.getkey(), e.getvalue()); return multimap; } usage:
public static void main(string[] args) { map<string, list<integer>> map = new hashmap<string, list<integer>>(); map.put("hello", arrays.aslist(1, 2)); map.put("world!", arrays.aslist(3)); multimap<string, integer> multimap = tomultimap(map); iterator<entry<string, integer>> = multimap.entries().iterator(); while (it.hasnext()) system.out.println(it.next()); } outputs:
hello=1 hello=2 world=3
Comments
Post a Comment