`
wei5201
  • 浏览: 185012 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

集合操作工具类CollectionUtils

阅读更多
使用CollectionUtils中四个方法之一执行集合操作.这四种分别是union(),intersection();disjunction(); subtract();
下列例子就是演示了如何使用上述四个方法处理两个Collection;
例子:使用:CollectionUtils union(),intersection();disjunction(); subtract();
注: 这些方法都是数学的集合算法
import java.util.*;
String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" };
String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" };

List a = Arrays.asList( arrayA );
List b = Arrays.asList( arrayB );

Collection union = CollectionUtils.union( a, b );  //并集
Collection intersection = CollectionUtils.intersection( a, b ); //交集
Collection disjunction = CollectionUtils.disjunction( a, b ); //析取
Collection subtract = CollectionUtils.subtract( a, b ); //差集

Collections.sort( union );
Collections.sort( intersection );
Collections.sort( disjunction );
Collections.sort( subtract );


System.out.println( "A: " + ArrayUtils.toString( a.toArray( ) ) );
System.out.println( "B: " + ArrayUtils.toString( b.toArray( ) ) );
System.out.println( "Union: " + ArrayUtils.toString( union.toArray( ) ) );
System.out.println( "Intersection: " +
ArrayUtils.toString( intersection.toArray( ) ) );
System.out.println( "Disjunction: " +
ArrayUtils.toString( disjunction.toArray( ) ) );
System.out.println( "Subtract: " + ArrayUtils.toString( subtract.toArray( ) ) );



The previous example performs these four operations on two List objects, a and b, printing the results with ArrayUtils.toString( ):

结果:
A: {1,2,2,2,3,3,4,5}
B: {3,4,4,5,6,7}
Union: {1,2,2,2,3,3,4,4,5,6,7}
Intersection: {3,4,5}
Disjunction: {1,2,2,2,3,4,6,7}
Subtract: {1,2,2,2,3}
分享到:
评论
1 楼 ae6623 2016-01-06  
@Test
	//@Ignore
	public void test2(){
		String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" };
		String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" };

		List a = Arrays.asList(arrayA);
		List b = Arrays.asList( arrayB );

		List union = new ArrayList(CollectionUtils.union(a, b));  //并集
		List intersection = new ArrayList(CollectionUtils.intersection( a, b )); //交集
		List disjunction = new ArrayList(CollectionUtils.disjunction( a, b )); //析取
		List subtract = new ArrayList(CollectionUtils.subtract( a, b )); //差集

		Collections.sort(union);
		Collections.sort( intersection );
		Collections.sort( disjunction );
		Collections.sort( subtract );


		System.out.println( "A: " + a.toString() );
		System.out.println( "B: " + b.toString() );
		System.out.println( "Union: " + union.toString());
		System.out.println( "Intersection: " +
				intersection.toString() );
		System.out.println( "Disjunction: " +
				disjunction.toString() );
		System.out.println( "Subtract: " + subtract.toString() );
	}


=>

A: [1, 2, 3, 3, 4, 5]
B: [3, 4, 4, 5, 6, 7]
Union: [1, 2, 3, 3, 4, 4, 5, 6, 7]
Intersection: [3, 4, 5]
Disjunction: [1, 2, 3, 4, 6, 7]
Subtract: [1, 2, 3]

相关推荐

Global site tag (gtag.js) - Google Analytics