Intersection and union of ArrayLists in Java

后端 未结 24 2616
离开以前
离开以前 2020-11-22 06:05

Are there any methods to do so? I was looking but couldn\'t find any.

Another question: I need these methods so I can filter files. Some are AND filter

24条回答
  •  暖寄归人
    2020-11-22 06:51

    Collection (so ArrayList also) have:

    col.retainAll(otherCol) // for intersection
    col.addAll(otherCol) // for union
    

    Use a List implementation if you accept repetitions, a Set implementation if you don't:

    Collection col1 = new ArrayList(); // {a, b, c}
    // Collection col1 = new TreeSet();
    col1.add("a");
    col1.add("b");
    col1.add("c");
    
    Collection col2 = new ArrayList(); // {b, c, d, e}
    // Collection col2 = new TreeSet();
    col2.add("b");
    col2.add("c");
    col2.add("d");
    col2.add("e");
    
    col1.addAll(col2);
    System.out.println(col1); 
    //output for ArrayList: [a, b, c, b, c, d, e]
    //output for TreeSet: [a, b, c, d, e]
    

提交回复
热议问题