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