import org.apache.commons.collections.CollectionUtils;
public static void main(String [] args){ List<Long> aList = new ArrayList<>(); aList.add(1L); aList.add(2L); aList.add(3L); aList.add(4L); aList.add(5L); List<Long> bList = new ArrayList<>(); bList.add(3L); bList.add(4L); bList.add(5L); bList.add(6L); //交集的补集 Collection disjunction = CollectionUtils.disjunction(aList, bList); // 交集 Collection intersection = CollectionUtils.intersection(aList, bList); Collection collection = CollectionUtils.removeAll(aList, bList); Collection collection1 = CollectionUtils.retainAll(aList, bList); // 并集 Collection union = CollectionUtils.union(aList, bList); //集合相减 Collection subtract = CollectionUtils.subtract(aList, bList); System.out.println("交集的补集disjunction:"+disjunction); System.out.println("交集intersection:"+intersection); System.out.println("collection:"+collection); System.out.println("collection1:"+collection1); System.out.println("并集union:"+union); System.out.println("集合相减subtract:"+subtract); }
结果:
交集的补集disjunction:[1, 2, 6]
交集intersection:[3, 4, 5]
collection:[1, 2]
collection1:[3, 4, 5]
并集union:[1, 2, 3, 4, 5, 6]
集合相减subtract:[1, 2]