1

我有两张地图:

Map<String, Sample> newMap = convertJSONObjectToSampleMap(newMapStr);
Map<String, Sample> oldMap = convertJSONObjectToSampleMap(oldMapStr);

Sample是一些自定义类

newMap键:[1,2,3,4,5]oldMap键:[2,3,4,5,8]

获得它们之间差异的最佳方法是什么,.e, get Samples with keys: 1and 8?

我想使用Collections和提取Set<>

Set<String> newSet = newMap.keySet();
Set<String> oldSet = oldMap.keySet();

谢谢,

4

3 回答 3

6

您想要的称为对称差异。

在此处输入图像描述

Guava 提供了这样一种方法。

Set<String> diff = Sets.symmetricDifference(newSet, oldSet);

然后只需遍历集合即可获取样本。

List<Sample> samples = new ArrayList<>();
for(String key : diff){
    if(oldMap.containsKey(key)){
        samples.add(oldMap.get(key));
    } else {
        samples.add(newMap.get(key));
    }
}

你也可以用官方的API来做,基本上对称的区别是并集减去两组的交集,但是为什么要重新发明轮子呢?

如果您只使用一种方法,则使用外部依赖项可能会很糟糕,但 Guava 提供了许多必须的有用功能。

于 2014-05-03T14:26:58.200 回答
2

循环浏览一张地图并进行比较。

它只是O(n)循环通过其中一张地图。考虑这段代码:

for (String key: oldMap.keySet()) {
    if (newMap.containsKey(key))
        newMap.remove(key);
    else
        newMap.put(key, oldMap.get(key));
}

并且newMap现在将只包含两个集合中的唯一条目。它为您提供键和值,因此所有数据都在一个地方。它很快,因为您只需要循环遍历其中一张地图中的键,而不必创建集合。

于 2014-05-03T14:28:06.100 回答
2

如果您只对按键感兴趣,请使用这样的功能:

public static Set<String> getDiff(Map<String,Object> mapA, Map<String,Object> mapB) {
    Set<String> diff = mapA.keySet();
    for (String s: mapB.keySet()) {
        if (diff.contains(s))
            diff.remove(s);
        else
            diff.add(s);
    }
    return diff;
}

对完整的 diff Map 使用以下函数(不影响您现有的 Map 对象):

public static Map<String,Object> getDiff(Map<String,Object> mapA, Map<String,Object> mapB) {
   Map<String,Object> diff = new HashMap<String,Object>();
   diff.putAll(mapA);
   for (String s: mapB.keySet()) {
       if (diff.containsKey(s))
           diff.remove(s);
       else
           diff.put(s, mapB.get(s));
   }
   return diff;
}
于 2014-05-03T14:38:57.083 回答