在Java中区分和比较Map值的有效方法

时间:2020-08-27 11:41:17

标签: java

我有2个LinkedHashMap,我正在尝试进行比较,并且应该显示基于键的值是否存在差异。

srcMap={Col1=Val1,Col2=Val2,Col3=Val3,Col4=ValDiff,,Col5=Val3}
dstMap={Col1=Val1,Col2=Val2,Col3=Val3,Col4=Val3,,Col5=ValMisMatch}

我正在尝试使用循环的方式。

Iterator<Map.Entry<String,String>> itSrc=srcMap.entrySet().iterator();
while(itSrc.hasNext()){
String srcKey=itSrc.next().getKey();
String srcValue=srcMap.get(srcKey);
String dstValue=dstMap.get(srcKey);
if(!srcValue.equals(dstValue))
  //printing value and corresponding key
}

我正在寻找的是,有没有比这更好/更快的方法了?

3 个答案:

答案 0 :(得分:2)

我认为这样的话会很有趣

for(Map.Entry<String,String> entry : srcMap.entrySet()) {
    String key = entry.getKey();
    if (dstMap.contains(key)) {
        if (entry.getValue().equals(dstMap.get(key)) {
            continue;
        }
    }

    System.out.println("Your desired output");
}

UPD。如果您的程序不希望有人将null映射到某个键:

for(Map.Entry<String,String> entry : srcMap.entrySet()) {
    String key = entry.getKey();
    
    if (entry.getValue().equals(dstMap.get(key)) {
        continue;
    }

    System.out.println(
        "Key:" + key + 
        "; Values differ:" + entry.getValue() + 
        "," + dstMap.get(key)
    );
}

请注意,map.get(key)在两种情况下可能会返回null-有人将null映射到键,或者键的值不存在

答案 1 :(得分:1)

您可以使用Stream API。使用filter过滤map的不匹配值,然后使用forEach

打印值
srcMap.entrySet()
      .stream()
      .filter(e -> !e.getValue().equals(dstMap.get(e.getKey())))
      .forEach(e -> System.out.println(e.getValue() + " "+ dstMap.get(e.getKey())));

答案 2 :(得分:1)

您可以使用番石榴:

https://guava.dev/releases/20.0/api/docs/com/google/common/collect/MapDifference.html

例如,如果

import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;

Map<String,String> srcMap = new LinkedHashMap<>();
srcMap.put("Col1","Val1");
srcMap.put("Col2","Val2");
srcMap.put("Col3","Val3");
srcMap.put("Col4","ValDiff");
srcMap.put("Col5","Val3");

Map<String,String> dstMap = new LinkedHashMap<>();
dstMap.put("Col1","Val1");
dstMap.put("Col2","Val2");
dstMap.put("Col3","Val3");
dstMap.put("Col4","Val3");
dstMap.put("Col5","ValMisMatch");

MapDifference<String, String> diff = Maps.difference(srcMap, dstMap);
System.out.println("All Differences: " + diff.entriesDiffering());
System.out.println("All Common Entries: " + diff.entriesInCommon());

可以帮助您

All Differences: {Col4=(ValDiff, Val3), Col5=(Val3, ValMisMatch)}
All Common Entries: {Col1=Val1, Col2=Val2, Col3=Val3}
相关问题