Intersection and union of ArrayLists in Java

后端 未结 24 2172
离开以前
离开以前 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:49

    You can use the methods:

    CollectionUtils.containsAny and CollectionUtils.containsAll

    from Apache Commons.

    0 讨论(0)
  • 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<String> col1 = new ArrayList<String>(); // {a, b, c}
    // Collection<String> col1 = new TreeSet<String>();
    col1.add("a");
    col1.add("b");
    col1.add("c");
    
    Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}
    // Collection<String> col2 = new TreeSet<String>();
    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]
    
    0 讨论(0)
  • 2020-11-22 06:52

    In Java 8, I use simple helper methods like this:

    public static <T> Collection<T> getIntersection(Collection<T> coll1, Collection<T> coll2){
        return Stream.concat(coll1.stream(), coll2.stream())
                .filter(coll1::contains)
                .filter(coll2::contains)
                .collect(Collectors.toSet());
    }
    
    public static <T> Collection<T> getMinus(Collection<T> coll1, Collection<T> coll2){
        return coll1.stream().filter(not(coll2::contains)).collect(Collectors.toSet());
    }
    
    public static <T> Predicate<T> not(Predicate<T> t) {
        return t.negate();
    }
    
    0 讨论(0)
  • 2020-11-22 06:53

    If you had your data in Sets you could use Guava's Sets class.

    0 讨论(0)
  • 2020-11-22 06:54

    You can use commons-collections4 CollectionUtils

    Collection<Integer> collection1 = Arrays.asList(1, 2, 4, 5, 7, 8);
    Collection<Integer> collection2 = Arrays.asList(2, 3, 4, 6, 8);
    
    Collection<Integer> intersection = CollectionUtils.intersection(collection1, collection2);
    System.out.println(intersection); // [2, 4, 8]
    
    Collection<Integer> union = CollectionUtils.union(collection1, collection2);
    System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8]
    
    Collection<Integer> subtract = CollectionUtils.subtract(collection1, collection2);
    System.out.println(subtract); // [1, 5, 7]
    
    0 讨论(0)
  • 2020-11-22 06:55
    • retainAll will modify your list
    • Guava doesn't have APIs for List (only for set)

    I found ListUtils very useful for this use case.

    Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.

    ListUtils.intersection(list1, list2)

    0 讨论(0)
提交回复
热议问题