`
wb284551926
  • 浏览: 538701 次
文章分类
社区版块
存档分类
最新评论

集合操作工具类CollectionUtils

 
阅读更多

使用CollectionUtils中四个方法之一执行集合操作.这四种分别是union(),intersection();disjunction(); subtract();
下列例子就是演示了如何使用上述四个方法处理两个Collection;
例子:使用:CollectionUtils union(),intersection();disjunction(); subtract();
注: 这些方法都是数学的集合算法

Java代码  收藏代码
  1. import java.util.*;  
  2. String[] arrayA = new String[] { "1""2""3""3""4""5" };  
  3. String[] arrayB = new String[] { "3""4""4""5""6""7" };  
  4.   
  5. List a = Arrays.asList( arrayA );  
  6. List b = Arrays.asList( arrayB );  
  7.   
  8. Collection union = CollectionUtils.union( a, b );  //并集  
  9. Collection intersection = CollectionUtils.intersection( a, b ); //交集  
  10. Collection disjunction = CollectionUtils.disjunction( a, b ); //析取  
  11. Collection subtract = CollectionUtils.subtract( a, b ); //差集  
  12.   
  13. Collections.sort( union );  
  14. Collections.sort( intersection );  
  15. Collections.sort( disjunction );  
  16. Collections.sort( subtract );  
  17.   
  18.   
  19. System.out.println( "A: " + ArrayUtils.toString( a.toArray( ) ) );  
  20. System.out.println( "B: " + ArrayUtils.toString( b.toArray( ) ) );  
  21. System.out.println( "Union: " + ArrayUtils.toString( union.toArray( ) ) );  
  22. System.out.println( "Intersection: " +  
  23. ArrayUtils.toString( intersection.toArray( ) ) );  
  24. System.out.println( "Disjunction: " +  
  25. ArrayUtils.toString( disjunction.toArray( ) ) );  
  26. 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 楼 soho00147 2017-03-18  
结果错误,应该是

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