2017-03-16 142 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); 
}