如何比较两个哈希映射?

res*_*shu 11 java

如何在键的帮助下比较两个哈希映射中的值?由于键是相同的,而值是非.并返回每个键比较的布尔结果.喜欢:

map1=[1,res]
[2,tr]
[3,677]
[4,cv]  

map2=[1,res]
[2,cd]
[3,677]
[4,fs]
Run Code Online (Sandbox Code Playgroud)

它应该归还我

true
false
true
false
Run Code Online (Sandbox Code Playgroud)

Sea*_*oyd 9

这是一个生成结果Map的方法(键到布尔的Map).无论键和键排序顺序如何,它都能很好地发挥作用:

/**
 * Works with any two maps with common key / value types.
 * The key type must implement Comparable though (for sorting).
 * Returns a map containing all keys that appear in either of the supplied maps.
 * The values will be true if and only if either
 *   - map1.get(key)==map2.get(key) (values may be null) or
 *   - map1.get(key).equals(map2.get(key)).
 */
public static <K extends Comparable<? super K>, V>
Map<K, Boolean> compareEntries(final Map<K, V> map1,
    final Map<K, V> map2){
    final Collection<K> allKeys = new HashSet<K>();
    allKeys.addAll(map1.keySet());
    allKeys.addAll(map2.keySet());
    final Map<K, Boolean> result = new TreeMap<K, Boolean>();
    for(final K key : allKeys){
        result.put(key,
            map1.containsKey(key) == map2.containsKey(key) &&
            Boolean.valueOf(equal(map1.get(key), map2.get(key))));
    }
    return result;
}

private static boolean equal(final Object obj1, final Object obj2){
    return obj1 == obj2 || (obj1 != null && obj1.equals(obj2));
}
Run Code Online (Sandbox Code Playgroud)

用法:

public static void main(final String[] args){
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, null);
    map1.put(2, "Different");
    map1.put(3, "Same");
    map1.put(4, "First Map only");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(3, "Same");
    map2.put(1, null);
    map2.put(2, "Yup, different");
    map2.put(5, "Second Map only");
    final Map<Integer, Boolean> comparisonResult =
        compareEntries(map1, map2);
    for(final Entry<Integer, Boolean> entry : comparisonResult.entrySet()){
        System.out.println("Entry:" + entry.getKey() + ", value: "
            + entry.getValue());
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

条目:1,值:true
条目:2,值:false
条目:3,值:true
条目:4,值:false
条目:5,值:false


Tim*_*ote 5

我从这个(可能是重复的)问题被引导到此处,并且惊讶地发现答案中没有提到Google Guava.

而不是重新发明轮子,使用方便的Maps.difference方法.


Kel*_*Kel 2

您可以获取一个映射的键(使用keySet()方法),迭代它们,从两个映射中获取值(使用get()方法),然后比较它们。

此外,您可以使用values()方法获取一个映射中的所有键值对,迭代它并将值与另一个映射中的值进行比较。