Java tutorial
//package com.java2s; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Main { /** * Returns a collection with the common elements in c1 and c2 * @param <T> * @param c1 * @param c2 * @return */ public static <T> Collection<T> intersect(Collection<T> c1, Collection<T> c2) { if (c1.isEmpty() || c2.isEmpty()) { return Collections.emptySet(); } if (!(c2 instanceof Set) && (c1 instanceof Set || c1.size() > c2.size())) { //swap Collection<T> tmp = c1; c1 = c2; c2 = tmp; } Collection<T> result = new HashSet<T>(); for (T obj : c1) { if (c2.contains(obj)) { result.add(obj); } } return result; } }