CollectionUtils取交集,并集和差集
import org.apache.commons.collections.CollectionUtils;
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
public static void main(String[] args) {
List<String> listA = new ArrayList<String>();
listA.add("a");
listA.add("b");
listA.add("b");
listA.add("c");
List<String> listB = new ArrayList<String>();
listB.add("a");
listB.add("e");
listB.add("f");
System.out.println("集合A:"+listA);
System.out.println("集合B:"+listB);
System.out.println("------------------------");
//并集
Collection<String> union = CollectionUtils.union(listA, listB);
System.out.println("并集:"+union);
//交集
Collection<String> intersection = CollectionUtils.intersection(listA, listB);
System.out.println("交集:"+intersection);
//交集的补集
Collection<String> disjunction = CollectionUtils.disjunction(listA, listB);
System.out.println("交集的补集 :"+disjunction);
//差集(集合相减)
Collection<String> subtract = CollectionUtils.subtract(listA, listB);
System.out.println("差集(集合相减) :"+subtract);
}
集合A:[a, b, b, c]
集合B:[a, e, f]
------------------------
并集:[a, b, b, c, e, f]
交集:[a]
交集的补集 :[b, b, c, e, f]
差集(集合相减) :[b, b, c]