Java Programming Tutorials

Java programming tutorials with many code examples!

Java contains any


How to check that a collection in Java contains any of elements from some other collection? It’s very common problem when working on Sets, but also applicable to Java Lists and other collections.

Sometimes problems are modeled in a way that one can work on them using Set Theory. One of common operations on sets, and as a matter of fact, on different types of collections, is to find that that two Sets/Lists/Maps/Collections are completely different, so have no common elements.


The operation returns true if two collections have no common elements. In Java contains any is implemented as Collections.disjoint(Collection<?> c1, Collection<?> c2) and works as in the following Java example:


import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CollectionsDisjoint {

    public static void main(String[] args) {
        List<String> c1 = Arrays.asList("effective", "java");
        Set<String> c2 = new HashSet<>(Arrays.asList("java", "tutorial"));

        areDifferent(c1, c2);

        areDifferent(c1, Arrays.asList("clojure", "scala"));

    private static void areDifferent(Collection<String> c1,
                                     Collection<String> c2) {
        // In other words: have _NO_ common elements:
        System.out.printf("%s and %s are completely different: %s%n",
                c1, c2, Collections.disjoint(c1, c2));

In the code above we’ve used Java List as one collection and Java Set as the other. Collections.disjoint(Collection<?> c1, Collection<?> c2) can compare any types of collections, but they have to have elements eligible for both types of collections (simplifying – of the same type).

And the result of running the above Java example:

[effective, java] and [[java, tutorial]] are completely different: false
[effective, java] and [[clojure, scala]] are completely different: true
Was it helpful? Share!