Tha*_*nga 5 java collections data-structures
迭代下面两张地图的最佳方法是什么?我想比较两个作为字符串的地图值,并且必须获取键和值.
HashMap<String, String> map1;
HashMap<String, String> map2;
Run Code Online (Sandbox Code Playgroud)
Lou*_*man 16
确实没有比这更好的选择了
for (Map.Entry<String, String> entry1 : map1.entrySet() {
String key = entry1.getKey();
String value1 = entry1.getValue();
String value2 = map2.get(key);
// do whatever with value1 and value2
}
Run Code Online (Sandbox Code Playgroud)
根据您究竟要做什么,有几个合理的选择:
只需比较两张地图的内容
Guava提供了一个Maps.difference()实用程序,它为您提供了一个MapDifference实例,让您可以准确地检查两个地图之间的相同或不同之处。
同时迭代它们的条目
如果您只想同时迭代两个映射中的条目,这与迭代任何其他Collection. 这个问题更详细,但基本的解决方案如下所示:
Preconditions.checkState(map1.size() == map2.size());
Iterator<Entry<String, String>> iter1 = map1.entrySet().iterator();
Iterator<Entry<String, String>> iter2 = map2.entrySet().iterator();
while(iter1.hasNext() || iter2.hasNext()) {
Entry<String, String> e1 = iter1.next();
Entry<String, String> e2 = iter2.next();
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,不能保证这些条目的顺序相同(因此很e1.getKey().equals(e2.getKey())可能是错误的)。
迭代它们的键以配对它们的值
如果您需要将键对齐,请遍历两个映射键的并集:
for(String key : Sets.union(map1.keySet(), map2.keySet()) {
// these could be null, if the maps don't share the same keys
String value1 = map1.get(key);
String value2 = map2.get(key);
...
}
Run Code Online (Sandbox Code Playgroud)