比较HashMaps的匹配和不匹配

时间:2017-03-16 16:04:01

标签: java collections hashmap comparison

我有两个HashMaps预计会保留相同的键,但期望它们的值存在一些差异,并且源/目标可能不包含密钥。

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

我希望生成一个报告,其中包含密钥Matched数据值,密钥Mismatched数据值,最后Keys exist in only one map

使用Java 8&#39; computeIfPresent()computeIfAbsent(),我该如何实现?我需要遍历source地图,检查key地图中是否存在target,如果存在,则检查值是否匹配。匹配时,将结果输出到匹配的集合。当不匹配时,输出到不匹配的容器,最后输出目标中不存在密钥。

1 个答案:

答案 0 :(得分: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);
}