2017-03-16 197 views
-1

我有两个HashMaps,预计将持有的键是相同,但期望它们的值有些差异,也许源/目标不包含密钥。比较哈希映射的匹配和不匹配

Map<String, Double> source = repository.getSourceData(); 
    Map<String, Double> target = repository.getTargetData(); 

我期待产生与键的键Matched数据值,Mismatched数据值,最后Keys exist in only one map的报告。

使用Java 8的computeIfPresent()computeIfAbsent(),我该如何做到这一点?我需要遍历source地图,检查target地图中是否存在key,如果存在,则检查值是否匹配。匹配时,将结果输出到匹配的集合。当不匹配时,输出到不匹配的容器,最后输出目标中没有键。

+0

请取[旅游](http://stackoverflow.com/tour),看看周围,并通过阅读[帮助中心](http://stackoverflow.com/help),特别是[我如何问一个好问题?](http://stackoverflow.com/help/how-to-ask)和[哪些主题可以我问这里?](http://stackoverflow.com/help/on-topic)。 –

回答

1

我不认为computeIfPresent或computeIfAbsent适用于此:

Map<String, Double> source = repository.getSourceData(); 
Map<String, Double> target = repository.getTargetData(); 

Map <String, Double> matched = new HashMap<>(); 
Map <String, List<Double>> mismatched = new HashMap<>(); 
Map <String, String> unmatched = new HashMap<>(); 
for (String keySource : source.keySet()) { 
    Double dblSource = source.get(keySource); 
    if (target.containsKey(keySource)) { // keys match 
     Double dblTarget = target.get(keySource); 
     if (dblSource.equals(dblTarget)) { // values match 
      matched.put(keySource, dblSource); 
     } else { // values don't match 
      mismatched.put(keySource, new ArrayList<Double>(Arrays.toList(dblSource, dblTarget))); 
     } 
    } else { // key not in target 
     unmatched.put(keySource, "Source"); 
    } 
} 
for (String keyTarget : target.keySet()) { // we only need to look for unmatched 
    Double dblTarget = target.get(keyTarget); 
    if (!source.containsKey(keyTarget)) { 
     unmatched.put(keyTarget, "Target"); 
    } 
} 

// print out matched 
System.out.println("Matched"); 
System.out.println("======="); 
System.out.println("Key\tValue"); 
System.out.println("======="); 
for (String key : matched.keySet()) { 
    System.out.println(key + "\t" + matched.get(key).toString()); 
} 

// print out mismatched 
System.out.println(); 
System.out.println("Mismatched"); 
System.out.println("======="); 
System.out.println("Key\tSource\tTarget"); 
System.out.println("======="); 
for (String key : mismatched.keySet()) { 
    List<Double> values = mismatched.get(key); 
    System.out.println(key + "\t" + values.get(0) + "\t" + values.get(1)); 
} 

// print out unmatched 
System.out.println(); 
System.out.println("Unmatched"); 
System.out.println("======="); 
System.out.println("Key\tWhich\tValue"); 
System.out.println("======="); 
for (String key : unmatched.keySet()) { 
    String which = unmatched.get(key); 
    Double value = null; 
    if ("Source".equals(which)) { 
     value = source.get(key); 
    } else { 
     value = target.get(key); 
    } 
    System.out.println(key + "\t" + which + "\t" + value); 
}