Java - Iterating over a Map which contains a List

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.)


I recommend iterating over Map.entrySet() as it is faster (you have both, the key and the value, found in one step).

Map<String, List<String>> m = new HashMap<String, List<String>>();

m.put("list1", Arrays.asList("s1", "s2", "s3"));

for (Map.Entry<String, List<String>> me : m.entrySet()) {
  String key = me.getKey();
  List<String> valueList = me.getValue();
  System.out.println("Key: " + key);
  System.out.print("Values: ");
  for (String s : valueList) {
    System.out.print(s + " ");
  }
}

And the output is, as expected:

Key: list1
Values: s1 s2 s3 

Tags:

Java

List

Set

Map