Intersection of java.util.Map

亡梦爱人 提交于 2019-11-26 11:19:51

问题


Is there a method in java.util.Map or any util to perform an intersection on two maps? (To intersect two maps by the \"keys\")

I am not able to find any. I can always implement my own intersection logic, but I was hoping there is already some operation in one of the java.util.* classes that would do this.


回答1:


How about:

Map map1 = ...;
Map map2 = ...;
Map result = new ...(map1);
result.keySet().retainAll(map2.keySet());

or:

Map map1 = ...;
Map map2 = ...;
Set result = new ...(map1.keySet());
result.retainAll(map2.keySet());



回答2:


If you're using Guava, you can use Maps.difference to get a MapDifference object, from which you can extract the entriesInCommon() and entriesDiffering() as maps. (Disclosure: I contribute to Guava.)




回答3:


Guava's Sets.intersection(Set, Set) should do the job, with the keySet of each Map passed in as parameters.




回答4:


I would recommend apache collectionUtils#intersection

Do the following:

 Collection intersection=    
      CollectionUtils.intersection(map1.keySet(),map2.keySet());



回答5:


To test for intersection you can use the containsAll() operation. Which 'Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.'

To get a collection of these intersecting elements you can use the retainAll() operation instead.

These methods are both found here

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Set.html




回答6:


Loop over one map's keys, see if they're in the second map:

private Map getIntersection(Map mapOne, Map mapTwo)
{
    Map intersection = new HashMap();
    for (Object key: mapOne.keySet())
    {
        if (mapTwo.containsKey(key))
           intersection.put(key, mapOne.get(key));
    }
    return intersection;
}


来源:https://stackoverflow.com/questions/13180488/intersection-of-java-util-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!