问题
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