guava set,map 的交集, 并集, 差集

 

 

 

{// set的交集, 并集, 差集
    HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);
    HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);
    //并集
    Sets.SetView<Integer> union = Sets.union(setA, setB);
    log.info("union:" + union);
    //差集 setA-setB
    Sets.SetView<Integer> difference = Sets.difference(setA, setB);
    log.info("difference:" + difference);
    //交集
    Sets.SetView<Integer> intersection = Sets.intersection(setA, setB);
    log.info("intersection:" + intersection);
}

{//map的交集,并集,差集
    HashMap<String, Integer> mapA = Maps.newHashMap();
    mapA.put("a", 1);
    mapA.put("b", 2);
    mapA.put("c", 3);
    HashMap<String, Integer> mapB = Maps.newHashMap();
    mapB.put("b", 20);
    mapB.put("c", 3);
    mapB.put("d", 4);
    MapDifference<String, Integer> mapDifference = Maps.difference(mapA, mapB);
    //mapA 和 mapB 相同的 entry
    System.out.println(mapDifference.entriesInCommon());
    //mapA 和 mapB key相同的value不同的 entry
    System.out.println(mapDifference.entriesDiffering());
    //只存在 mapA 的 entry
    System.out.println(mapDifference.entriesOnlyOnLeft());
    //只存在 mapB 的 entry
    System.out.println(mapDifference.entriesOnlyOnRight());
}

 

posted @ 2021-07-14 13:37  草木物语  阅读(996)  评论(0编辑  收藏  举报