Close

Java - How to find intersection of two or more collections?

[Last Updated: May 21, 2018]

Java Collections Java 

Following example shows how to find intersection of multiple collections.

public class CollectionIntersection {

  public static <T, C extends Collection<T>> C findIntersection(C newCollection,
                                                                Collection<T>... collections) {
      boolean first = true;
      for (Collection<T> collection : collections) {
          if (first) {
              newCollection.addAll(collection);
              first = false;
          } else {
              newCollection.retainAll(collection);
          }
      }
      return newCollection;
  }

  public static void main(String[] args) {
      List<Integer> l1 = List.of(1, 3, 5, 7, 9, 11, 13);
      List<Integer> l2 = List.of(1, 2, 3, 5, 8, 13);
      List<Integer> l3 = List.of(2, 3, 5, 7, 11, 13);
      Set<Integer> intersection = findIntersection(new HashSet<>(), l1, l2, l3);
      System.out.println(intersection);
  }
}
[3, 5, 13]

See Also