Apache common collection的使用(3)

来源:互联网 发布:vc打印机编程 编辑:程序博客网 时间:2024/06/10 15:45

集合的使用

并集

Collection collection =  CollectionUtils.union(set1, set2);

交集

collection = CollectionUtils.intersection(set1, set2);

差集

collection = CollectionUtils.subtract(set1, set2);

程序

package cn.others;import org.apache.commons.collections4.CollectionUtils;import java.util.Collection;import java.util.HashSet;import java.util.Set;/** * @author Duoduo * @version 1.0 * @date 2017/4/15 15:15 */public class Test6 {    public static void main(String[] args){        Set<Integer> set1 = new HashSet<Integer>();        set1.add(1);        set1.add(2);        set1.add(3);        set1.add(4);        Set<Integer> set2 = new HashSet<Integer>();        set2.add(3);        set2.add(4);        set2.add(5);        System.out.println("********* 并集 **********");        Collection collection =  CollectionUtils.union(set1, set2);        System.out.println(collection);        System.out.println("********* 交集 **********");        collection = CollectionUtils.intersection(set1, set2);        System.out.println(collection);        System.out.println("********* 差集 **********");        collection = CollectionUtils.subtract(set1, set2);        System.out.println(collection);    }}

运行结果

* 并集 **
[1, 2, 3, 4, 5]
* 交集 **
[3, 4]
* 差集 **
[1, 2]

0 0