Java - 迭代包含列表的地图 [英] Java - Iterating over a Map which contains a List
问题描述
第一次在这里,所以我希望这是有道理的!
First time here so I hope this makes sense!
我有一个Map,它包含一个字符串作为它的Key,一个字符串列表作为它的价值。我需要迭代地图中每个列表中包含的所有vlaues。
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,或者在这种情况下是List。我试过 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.
谢谢y'all!
推荐答案
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's ListMultimap
,这很像一个 Map< K,List< V>
,但具有更多的功能 - 包括一个收集和LT; V> values()
完全符合您的要求,将多功能中的所有值展平为一个集合。 (披露:我贡献了番石榴。)
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.)
这篇关于Java - 迭代包含列表的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!