map集合取並集,差集,交集


map集合取並集,差集,交集

前段時間需要用到取兩個集合的並集,差集,交集,在這貼下代碼記錄一下

1.獲取兩個map的並集

/**
 * 取Map集合的並集
 *
 * @param map1 大集合
 * @param map2 小集合
 * @return 兩個集合的並集
 */
public static Map<String, Object> getUnionSetByGuava(Map<String, Object> map1, Map<String, Object> map2) {
    Set<String> bigMapKey = map1.keySet();
    Set<String> smallMapKey = map2.keySet();
    Set<String> differenceSet = Sets.union(bigMapKey, smallMapKey);
    Map<String, Object> result = Maps.newHashMap();
    for (String key : differenceSet) {
        if (map1.containsKey(key)) {
            result.put(key, map1.get(key));
        } else {
            result.put(key, map2.get(key));
        }
    }
    return result;
}

2.獲取兩個map差集

/**
 * 取Map集合的差集
 *
 * @param bigMap   大集合
 * @param smallMap 小集合
 * @return 兩個集合的差集
 */
public static Map<String, Object> getDifferenceSetByGuava(Map<String, Object> bigMap, Map<String, Object> smallMap) {
    Set<String> bigMapKey = bigMap.keySet();
    Set<String> smallMapKey = smallMap.keySet();
    Set<String> differenceSet = Sets.difference(bigMapKey, smallMapKey);
    Map<String, Object> result = Maps.newHashMap();
    for (String key : differenceSet) {
        result.put(key, bigMap.get(key));
    }
    return result;
}

3.獲取連個map交集

/**
 * 取Map集合的交集(String,String)
 *
 * @param map1 大集合
 * @param map2 小集合
 * @return 兩個集合的交集
 */
public static Map<String, Object> getIntersectionSetByGuava(Map<String, Object> map1, Map<String, Object> map2) {
    Set<String> bigMapKey = map1.keySet();
    Set<String> smallMapKey = map2.keySet();
    Set<String> differenceSet = Sets.intersection(bigMapKey, smallMapKey);
    Map<String, Object> result = Maps.newHashMap();
    for (String key : differenceSet) {
        result.put(key, map1.get(key));
    }
    return result;
}
https://blog.csdn.net/qq_37116471/article/details/86488411


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM