Posted on 2010-05-17 23:29
断点 阅读(623)
评论(0) 编辑 收藏 所属分类:
Apache
CollectionUtils 中四个方法对集合操作: union(),intersection(),disjunction();,subtract()。
1import java.util.Arrays;
2import java.util.Collection;
3import java.util.Collections;
4import java.util.List;
5
6import org.apache.commons.collections.CollectionUtils;
7import org.apache.commons.lang.ArrayUtils;
8
9public class TestCollectionUtils {
10 @SuppressWarnings("unchecked")
11 public static void main(String[] args) {
12 String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" };
13 String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" };
14
15 List<String> a = Arrays.asList(arrayA);
16 List<String> b = Arrays.asList(arrayB);
17 // 并集
18 Collection<String> union = CollectionUtils.union(a, b);
19 // 交集
20 Collection<String> intersection = CollectionUtils.intersection(a, b);
21 // 交集的补集
22 Collection<String> disjunction = CollectionUtils.disjunction(a, b);
23 // 集合相减
24 Collection<String> subtract = CollectionUtils.subtract(a, b);
25
26 Collections.sort((List<String>) union);
27 Collections.sort((List<String>) intersection);
28 Collections.sort((List<String>) disjunction);
29 Collections.sort((List<String>) subtract);
30
31 System.out.println("A: " + ArrayUtils.toString(a.toArray()));
32 System.out.println("B: " + ArrayUtils.toString(b.toArray()));
33 System.out.println("--------------------------------------------");
34 System.out.println("Union(A, B): " + ArrayUtils.toString(union.toArray()));
35 System.out.println("Intersection(A, B): " + ArrayUtils.toString(intersection.toArray()));
36 System.out.println("Disjunction(A, B): " + ArrayUtils.toString(disjunction.toArray()));
37 System.out.println("Subtract(A, B): " + ArrayUtils.toString(subtract.toArray()));
38 }
39}
输出:
A: {1,2,3,3,4,5}
B: {3,4,4,5,6,7}
--------------------------------------------
Union(A, B): {1,2,3,3,4,4,5,6,7}
Intersection(A, B): {3,4,5}
Disjunction(A, B): {1,2,3,4,6,7}
Subtract(A, B): {1,2,3}
转载:http://blog.csdn.net/ofofw/archive/2009/06/26/4300964.aspx