我正在制作一个程序,该程序使用两个文本文件(两个表),并对它们执行基本的关系代数(并集、差值、交集和联接)。我正在使用 HashMap 来每次保存值(键/值),但我想知道如何为每个操作使用一个主“for 循环”而不是 4 个。 这是我的代码:
for (Map.Entry<Integer, String> htEntries : map.entrySet()) {
if(map2.containsKey(htEntries.getKey()) && map2.get(htEntries.getKey()).equals(htEntries.getValue())){
inter.put( htEntries.getKey(), htEntries.getValue());
}
}
for (Map.Entry<Integer, String> joinEntries : map.entrySet()) {
if(map2.containsKey(joinEntries.getKey())){
join.put( joinEntries.getKey(), joinEntries.getValue());
}
}
for (Map.Entry<Integer, String> diffEntries : map.entrySet()) {
if(!map2.containsKey(diffEntries.getKey())){
diff.put( diffEntries.getKey(), diffEntries.getValue());
}
}
for (Map.Entry<Integer, String> diffEntries2 : map2.entrySet()) {
if(!map.containsKey(diffEntries2.getKey())){
diff2.put( diffEntries2.getKey(), diffEntries2.getValue());
}
}
最佳答案
我认为你必须使用至少2个for循环,你可以这样做:
for (Map.Entry<Integer, String> htEntries : map.entrySet()) {
if(map2.containsKey(htEntries.getKey()) {
join.put( htEntries.getKey(), htEntries.getValue());
if (map2.get(htEntries.getKey()).equals(htEntries.getValue())) {
inter.put(htEntries.getKey(), htEntries.getValue());
}
} else {
diff.put( htEntries.getKey(), htEntries.getValue());
}
}
for (Map.Entry<Integer, String> diffEntries2 : map2.entrySet()) {
if(!map.containsKey(diffEntries2.getKey())){
diff2.put(diffEntries2.getKey(), diffEntries2.getValue());
}
}
关于java - 避免重复(for 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400205/