java - 避免重复(for 循环)

标签 java for-loop

我正在制作一个程序,该程序使用两个文本文件(两个表),并对它们执行基本的关系代数(并集、差值、交集和联接)。我正在使用 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/

相关文章:

java - 为什么SpringApplication通过配置加载ApplicationContextInitializer?

java - 用字符打印火车

c++ - 如何实现递增数据的循环

matlab - 如何遍历两个相同大小的矩阵并比较它们

c# - 如何在 C# 中使用 for 循环从队列中检索值?

java - 如何在java中创建一个每次迭代返回不同变量的循环?

java - 无法在我的pom中添加xmlunit作为依赖项

java - 设置 Java GUI 建筑和房间

java - 如何更改搜索框的标题?

java - 如何在连续的 for 循环之间传递变量值?