主要用它的isEmpty(final Collection<?> coll)静态方法来判断一个给定的集合是否为null或者是否长度为0。最近才发现此工具类还可以取集合的交集、并集、甚至差集,集合1:[1,2,3,4],集合2:[3,4,5,6]

      上面两个集合取交集的结果是[3,4],CollectionUtils工具类提供了Collection<O> intersection(final Iterable<? extends O> a, final Iterable<? extends O> b)静态方法来取交集,参数传两个集合,可以是list,也可以是set,甚至一个list,一个set;

      上面两个集合取并集的结果是[1,2,3,4,5,6],CollectionUtils工具类提供了Collection<O> union(final Iterable<? extends O> a, final Iterable<? extends O> b) ,参数同取交集类似;

      CollectionUtils工具类也提供了取差集的静态方法Collection<O> disjunction(final Iterable<? extends O> a, final Iterable<? extends O> b),如果操作上面两个集合的话(第一个集合减去第二个集合),结果是[1,2,5,6],这个效果其实是两个集合的并集减去这两个集合的交集。但是实际开发中,我们可能更想要得到[1,2],CollectionUtils工具类并没有提供能直接达到这种效果的方法,不过我们可以通过两个方法的合作来达到这种效果,即用第一个集合减去这两个集合的交集:

 

 

public static void main(String[] args) { 
    List<Integer> list1 = new ArrayList<Integer>(); 
    list1.add(1); 
    list1.add(2); 
    list1.add(3); 
    list1.add(4); 
   
    List<Integer> list2 = new ArrayList<Integer>(); 
    list2.add(3); 
    list2.add(4); 
    list2.add(5); 
    list2.add(6); 
   
    // 取交集[3, 4] 
    Collection<Integer> interColl = CollectionUtils.intersection(list1, list2); 
    System.out.println(interColl);// 打印出[3, 4] 
   
    // 取并集[1, 2, 3, 4, 5, 6] 
    Collection<Integer> unionColl = CollectionUtils.union(list1, list2); 
    System.out.println(unionColl);// 打印出[1, 2, 3, 4, 5, 6] 
   
    // 取差集[1,2] 
    Collection<Integer> disColl = CollectionUtils.disjunction(list1, interColl); 
    System.out.println(disColl);// 打印出[1, 2] 
    }  

 

posted on 2018-06-24 17:52  lshan  阅读(272)  评论(0编辑  收藏  举报