在 java 的同一个循环中迭代两个 hashmap 的最佳方法是什么?
What is the best way to iterate two hashmap in same loop in java?
一起迭代以下两个地图的最佳方法是什么?我想比较两个映射值,它们是字符串并且必须获取键和值。
HashMap<String, String> map1;
HashMap<String, String> map2;
真的没有比
更好的选择了
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
}
您可以这样做:
for (String key : map1.keySet()) {
if (map2.containsKey(key)) {
// do whatever
} else {
// map2 doesn't have entry with map1 key
}
}
根据您具体要做什么,有几个合理的选择:
比较两张图的内容就可以了
Guava provides a Maps.difference()
utility that gives you a MapDifference
实例让您准确检查两个地图之间的相同或不同之处。
同时迭代他们的条目
如果您只想同时遍历两个映射中的条目,这与遍历任何其他映射没有什么不同 Collection
。 This question 进行了更详细的介绍,但基本解决方案如下所示:
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();
...
}
请注意,不能保证这些条目的顺序相同(因此 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);
...
}
我的情况是地图大小相同
IntStream.range(0, map1.size()).forEach(i -> map1.get(i).equals(map2.get(i));
一起迭代以下两个地图的最佳方法是什么?我想比较两个映射值,它们是字符串并且必须获取键和值。
HashMap<String, String> map1;
HashMap<String, String> map2;
真的没有比
更好的选择了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
}
您可以这样做:
for (String key : map1.keySet()) {
if (map2.containsKey(key)) {
// do whatever
} else {
// map2 doesn't have entry with map1 key
}
}
根据您具体要做什么,有几个合理的选择:
比较两张图的内容就可以了
Guava provides a
Maps.difference()
utility that gives you aMapDifference
实例让您准确检查两个地图之间的相同或不同之处。同时迭代他们的条目
如果您只想同时遍历两个映射中的条目,这与遍历任何其他映射没有什么不同
Collection
。 This question 进行了更详细的介绍,但基本解决方案如下所示: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(); ... }
请注意,不能保证这些条目的顺序相同(因此
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); ... }
我的情况是地图大小相同
IntStream.range(0, map1.size()).forEach(i -> map1.get(i).equals(map2.get(i));