Java中对集合的并,交,联集,差操作

怎样求出两个集合中 相同元素的个数、不同的元素的个数 等等,这时可以用集合的并,交,联集,差进行操作;apache.commons.collections.CollectionUtils这个类提供了支持。

//并操作
public String collectionUnion(String[] arrayA, String[] arrayB){
String arrayC = "";
try {
    List a = Arrays.asList(arrayA);
    List b = Arrays.asList(arrayB);
    Collection union = CollectionUtils.union(a, b);
    arrayC=union.toArray().toString();
} catch (Exception ex){
   do something.......
}
return arrayC;
}

//交操作
public String collectionIntersection(String[] arrayA, String[] arrayB){
String arrayC = "";
try {
    List a = Arrays.asList(arrayA);
    List b = Arrays.asList(arrayB);
    Collection intersection = CollectionUtils.intersection(a, b);
    arrayC=intersection.toArray().toString();
} catch (Exception ex) {
    do something......
}
return arrayC;
}

//联集操作
public String collectionDisjunction(String[] arrayA, String[] arrayB) {
String arrayC = "";
try{
    List a = Arrays.asList(arrayA);
    List b = Arrays.asList(arrayB);
    Collection disjunction = CollectionUtils.disjunction(a, b);
    arrayC=disjunction.toArray().toString();
} catch (Exception ex){
   do something.......
}
return arrayC;
}

//实现差操作
public String collectionSubtract(String[] arrayA, String[] arrayB) {
String arrayC = "";
try {
    List a = Arrays.asList(arrayA);
    List b = Arrays.asList(arrayB);
    Collection subtract = CollectionUtils.subtract(a, b);
    arrayC=subtract.toArray().toString();
} catch (Exception ex) ...{
   do something.......

}
return arrayC;
}

你可能感兴趣的:(java,apache)