使用CollectionUtils工具取两个集合List的交集、补集、并集

import org.apache.commons.collections.CollectionUtils;

public class Test {
    public static void main(String[] args) {
        String[] arr1 = new String[]{"A", "B", "C", "D", "E", "F", "G"};
        String[] arr2 = new String[]{"D", "E", "F", "G", "H", "I", "J", "K"};
        List list1 = Arrays.asList(arr1);
        List list2 = Arrays.asList(arr2);
        System.out.println(ArrayUtils.toString(CollectionUtils.intersection(list1, list2))); // 交集
        System.out.println(ArrayUtils.toString(CollectionUtils.disjunction(list1, list2))); // 并集
        System.out.println(ArrayUtils.toString(CollectionUtils.subtract(list1, list2))); // A的补集
        System.out.println(ArrayUtils.toString(CollectionUtils.subtract(list2, list1))); // B的补集

    }
}



输出结果:
[D, E, F, G]
[A, B, C, H, I, J, K]
[A, B, C]
[H, I, J, K]

 

你可能感兴趣的:(Java基础)