Java - 遍历包含列表的地图

2022-01-17 00:00:00 list set java map

第一次来这里,所以我希望这是有道理的!

First time here so I hope this makes sense!

我有一个 Map,其中包含一个字符串作为它的键,以及一个字符串列表作为它的值.我需要遍历地图中每个列表中包含的所有变量.

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

这是我卡住的地方 - 网络上的大多数信息似乎都假设我希望从 Key 返回的值是一个简单的 String 或 Integer,而不是另一个 Set,或者在这种情况下是一个列表.我尝试了 theMap.values() 但这不起作用,我尝试了一个 forloop/for:eachloop,但这些都没有成功.

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.

谢谢大家!

推荐答案

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()) {
    ...
  }
}

也就是说,如果您可以选择,您可能会对 Guava 的 ListMultimap,这是一个很像 Map<K, List<V>>,但有更多的功能——包括 Collection<V>values() 的行为与您所要求的完全一样,扁平化";多重映射中的所有值到一个集合中.(披露:我为 Guava 做出了贡献.)

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

相关文章