Domanda

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.

È stato utile?

Soluzione

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());

Altri suggerimenti

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.)

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

I would recommend apache collectionUtils#intersection

Do the following:

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

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

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top