CollectionUtils工具类使用指南


CollectionUtils提供很多对集合的操作方法,常用的方法如下:(参考文章:http://www.open-open.com/code/view/1420470842125)

 1 import org.apache.commons.collections.CollectionUtils;
 2 import java.util.ArrayList;
 3 import java.util.List;
 4 public class CollectionUtilsTest {
 5      public static void main(String[] args) {
 6         List<Integer> a = new ArrayList<Integer>();
 7         List<Integer> b = null;
 8         List<Integer> c = new ArrayList<Integer>();
 9         c.add(5);
10         c.add(6);
11         //判断集合是否为空
12         System.out.println(CollectionUtils.isEmpty(a));   //true
13         System.out.println(CollectionUtils.isEmpty(b));   //true
14         System.out.println(CollectionUtils.isEmpty(c));   //false
15   
16         //判断集合是否不为空
17         System.out.println(CollectionUtils.isNotEmpty(a));   //false
18         System.out.println(CollectionUtils.isNotEmpty(b));   //false
19         System.out.println(CollectionUtils.isNotEmpty(c));   //true
20   
21         //两个集合间的操作
22         List<Integer> e = new ArrayList<Integer>();
23         e.add(2);
24         e.add(1);
25         List<Integer> f = new ArrayList<Integer>();
26         f.add(1);
27         f.add(2);
28         List<Integer> g = new ArrayList<Integer>();
29         g.add(12);
30         //比较两集合值
31         System.out.println(CollectionUtils.isEqualCollection(e,f));   //true
32         System.out.println(CollectionUtils.isEqualCollection(f,g));   //false
33   
34         List<Integer> h = new ArrayList<Integer>();
35         h.add(1);
36         h.add(2);
37         h.add(3);;
38         List<Integer> i = new ArrayList<Integer>();
39         i.add(3);
40         i.add(3);
41         i.add(4);
42         i.add(5);
43         //并集
44         System.out.println(CollectionUtils.union(i,h));  //[1, 2, 3, 3, 4, 5]
45         //交集
46         System.out.println(CollectionUtils.intersection(i,h)); //[3]
47         //交集的补集
48         System.out.println(CollectionUtils.disjunction(i,h)); //[1, 2, 3, 4, 5]
49         //e与h的差
50         System.out.println(CollectionUtils.subtract(h,i)); //[1, 2]
51         System.out.println(CollectionUtils.subtract(i,h)); //[3, 4, 5]
52     }
53 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM