How to Check If Two Collections Intersect in Java?


Given Two Collection Types in Java, we want to find out if two collections are overlapping (intersection) i.e. Any of the elements in one collection are found in another.

To improve the runtime performance, we iterate the collection with less elements and use the Collection.contains to check if another collection contains the elements in this collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Utils {
    public static boolean containsAny(Collection<?> coll1, Collection<?> coll2) {
        Iterator it;
        Object aColl1;
        if (coll1.size() < coll2.size()) {
            it = coll1.iterator();
            while (it.hasNext()) {
                aColl1 = it.next();
                if (coll2.contains(aColl1)) {
                    return true;
                }
            }
        } else {
            it = coll2.iterator();
            while (it.hasNext()) {
                aColl1 = it.next();
                if (coll1.contains(aColl1)) {
                    return true;
                }
            }
        }
        return false;
    }
}
class Utils {
    public static boolean containsAny(Collection<?> coll1, Collection<?> coll2) {
        Iterator it;
        Object aColl1;
        if (coll1.size() < coll2.size()) {
            it = coll1.iterator();
            while (it.hasNext()) {
                aColl1 = it.next();
                if (coll2.contains(aColl1)) {
                    return true;
                }
            }
        } else {
            it = coll2.iterator();
            while (it.hasNext()) {
                aColl1 = it.next();
                if (coll1.contains(aColl1)) {
                    return true;
                }
            }
        }
        return false;
    }
}

Example usage:

1
2
3
4
5
6
7
public class Main {
    public static void main(String[] args) {
        var data1 = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6, 7});
        var data2 = Arrays.asList(new Integer[] {8, 9, 3});
        System.out.println(Utils.containsAny(data1, data2)); // true
    }
}
public class Main {
    public static void main(String[] args) {
        var data1 = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6, 7});
        var data2 = Arrays.asList(new Integer[] {8, 9, 3});
        System.out.println(Utils.containsAny(data1, data2)); // true
    }
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
222 words
Last Post: Teaching Kids Programming - Depth First Search Algorithm to Find the Largest Land
Next Post: Teaching Kids Programming - Largest Odd Number in String

The Permanent URL is: How to Check If Two Collections Intersect in Java?

Leave a Reply