使用Google Guava工程中Sets工具包,實現集合的並集/交集/補集/差集

 @Test
    public static void testSets() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 4, 5, 6, 8);
        Set<Integer> set2 = Sets.newHashSet(2, 3, 4, 5, 6, 7, 9);

        //合集,並集   [1, 2, 4, 5, 6, 8, 3, 7, 9]
        Set<Integer> result1 = Sets.union(set1, set2);
        //交集          [2, 4, 5, 6]
        Set<Integer> result2 = Sets.intersection(set1, set2);
        //差集 1中有而2中沒有的  [1, 8]
        Set<Integer> result3 = Sets.difference(set1, set2);
        //相對差集 1中有2中沒有  2中有1中沒有的 取出來做結果 [1, 8, 3, 7, 9]
        Set<Integer> result4 = Sets.symmetricDifference(set1, set2);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章