Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Iterating over a Map which contains a List

Tags:

java

list

set

map

First time here so I hope this makes sense!

I have a Map which contains a String as it's Key, and a List of Strings as it's Value. I need to iterate over all vlaues contained within each List within the Map.

So, first I want to get the Keys, which works:

Set<String> keys = theMap.keySet();

This returns me a Set containing all my Keys. Great :)

This is where I've got stuck - most of the info on the web seems to assume that the values I'd want returned from the Key would be a simple String or Integer, not another Set, or in this case a List. I tried theMap.values() but that didn't work, and I tried a forloop / for:eachloop, and neither of those did the trick.

Thanks y'all!

like image 534
cmdrbob Avatar asked Apr 09 '12 15:04

cmdrbob


1 Answers

for(List<String> valueList : map.values()) {
  for(String value : valueList) {
    ...
  }
}

That's really the "normal" way to do it. Or, if you need the key as well...

for(Map.Entry<String, List<String>> entry : map.entrySet()) {
  String key = entry.getKey();
  for (String value : entry.getValue()) {
    ...
  }
}

That said, if you have the option, you might be interested in Guava's ListMultimap, which is a lot like a Map<K, List<V>>, but has a lot more features -- including a Collection<V> values() that acts exactly like what you're asking for, "flattening" all the values in the multimap into one collection. (Disclosure: I contribute to Guava.)

like image 61
Louis Wasserman Avatar answered Oct 11 '22 18:10

Louis Wasserman