7

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

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

因此,首先我想获得有效的密钥:

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

这将返回一个包含我所有密钥的集合。伟大的 :)

这就是我陷入困境的地方 - 网络上的大多数信息似乎都假设我希望从 Key 返回的值将是一个简单的字符串或整数,而不是另一个 Set,或者在这种情况下是一个 List。我试过theMap.values()了,但是没有用,我尝试了一个 forloop / for:eachloop,但这些都没有成功。

谢谢大家!

4

4 回答 4

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

这确实是“正常”的做法。或者,如果您还需要密钥...

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

也就是说,如果您可以选择,您可能会对Guava ListMultimap感兴趣,它很像 a Map<K, List<V>>,但具有更多功能 - 包括 aCollection<V> values()与您要求的完全一样,“扁平化”所有值在 multimap 中合并为一个集合。(披露:我为 Guava 做出了贡献。)

于 2012-04-09T15:52:04.123 回答
8

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 = Collections.singletonMap(
    "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 + " ");
  }
}

Or the same using the Java 8 API (Lambda functions):

m.entrySet().forEach(me -> {
    System.out.println("Key: " + me.getKey());
    System.out.print("Values: ");
    me.getValue().forEach(s -> System.out.print(s + " "));
});

Or with a little bit of Java Stream API mapping hardcore and method reference :-)

m.entrySet().stream().map(me -> {
    return "Key: " + me.getKey() + "\n"
        + "Values: " + me.getValue().stream()
            .collect(Collectors.joining(" "));
    })
    .forEach(System.out::print);

And the output is, as expected:

Key: list1
Values: s1 s2 s3 
于 2012-04-09T16:02:17.547 回答
0

你需要一个Map<String, List<String>>

左边String是key,右边List<String>是value,在这个例子中是ListsString的a

于 2012-04-09T15:52:29.077 回答
0

Java 8 API(lambda 函数)的另一个示例。
当你想迭代时:

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

theMap.forEach((key, value) -> {
       System.out.println("KEY: " + key);
       System.out.print("VALUES: ");
       value.forEach(System.out::println);
});
于 2022-02-11T10:00:56.210 回答