zoukankan      html  css  js  c++  java
  • JAVA集合操作的利器:CollectionUtils

    使用 CollectionUtils 中四个方法之一执行集合操作.这四种分别是 union(),intersection();disjunction(); subtract();

    下列例子就是演示了如何使用上述四个方法处理两个 Collection;

    import java.util.Arrays;      
    import java.util.Collection;      
    import java.util.Collections;      
    import java.util.List;              
    import org.apache.commons.collections.CollectionUtils;  import org.apache.commons.lang.ArrayUtils;            
      public class CollectionUtilsIntro {    
      @SuppressWarnings("unchecked")      
      public static void main(String[] args) {      
       String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" };      
       String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" };              
       List<String> a = Arrays.asList(arrayA);      
       List<String> b = Arrays.asList(arrayB);      
       //并集      
       Collection<String> union = CollectionUtils.union(a, b);      
       //交集      
       Collection<String> intersection = CollectionUtils.intersection(a, b);      
       //交集的补集      
       Collection<String> disjunction = CollectionUtils.disjunction(a, b);      
       //集合相减      
       Collection<String> subtract = CollectionUtils.subtract(a, b);              
       Collections.sort((List<String>) union);      
       Collections.sort((List<String>) intersection);      
       Collections.sort((List<String>) disjunction);      
       Collections.sort((List<String>) subtract);              
       System.out.println("A: " + ArrayUtils.toString(a.toArray()));      
       System.out.println("B: " + ArrayUtils.toString(b.toArray()));      
       System.out.println("--------------------------------------------");      
       System.out.println("Union(A, B): " + ArrayUtils.toString(union.toArray()));      
       System.out.println("Intersection(A, B): " + ArrayUtils.toString(intersection.toArray()));      
       System.out.println("Disjunction(A, B): " + ArrayUtils.toString(disjunction.toArray()));      
       System.out.println("Subtract(A, B): " + ArrayUtils.toString(subtract.toArray()));      
      }      
    }
     
      输出如下:
      A: {1,2,3,3,4,5}
      B: {3,4,4,5,6,7}
      --------------------------------------------
      Union(A, B): {1,2,3,3,4,4,5,6,7}
      Intersection(A, B): {3,4,5}
      Disjunction(A, B): {1,2,3,4,6,7}
      Subtract(A, B): {1,2,3}
  • 相关阅读:
    【Luogu1095】守望者的逃离
    python基础学习1-类相关内置函数
    python基础学习1-面向对象
    python基础学习1 -异常捕获
    python基础学习1-类,对象
    python基础学习1-正则表达式
    python基础学习1-反射
    python基础学习1-日志信息
    python基础学习1-生成器,递归函数
    python基础学习1-json,pickle的序列化和反序列化
  • 原文地址:https://www.cnblogs.com/google4y/p/3453414.html
Copyright © 2011-2022 走看看