简体   繁体   English

java.util.Map的交集

[英]Intersection of java.util.Map

Is there a method in java.util.Map or any util to perform an intersection on two maps? java.util.Map是否有方法或任何util在两个地图上执行交集? (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. 我总是可以实现自己的交集逻辑,但我希望在java.util.*类之一中已经可以进行此操作。

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

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. 如果使用的是Guava,则可以使用Maps.difference获取MapDifference对象,从中可以将entriesInCommon()entriesDiffering()提取为地图。 (Disclosure: I contribute to Guava.) (公开:我为番石榴做出了贡献。)

Guava的Sets.intersection(Set, Set)可以完成此工作,每个Map的keySet作为参数传入。

To test for intersection you can use the containsAll() operation. 要测试交叉点,可以使用containsAll()操作。 Which 'Returns true if this set contains all of the elements of the specified collection. 如果此集合包含指定集合的​​所有元素,则返回true。 If the specified collection is also a set, this method returns true if it is a subset of this set.' 如果指定的集合也是一个集合,则如果它是该集合的子集,则此方法返回true。

To get a collection of these intersecting elements you can use the retainAll() operation instead. 要获取这些相交元素的集合,可以改用keepAll()操作。

These methods are both found here 这些方法都可以在这里找到

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

I would recommend apache c ollectionUtils#intersection 我会建议apache c ollectionUtils#intersection

Do the following: 请执行下列操作:

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM