Java tutorial
//package com.java2s; import java.util.HashSet; import java.util.Set; public class Main { public static <T> Set<T> intersect(Set<T> sourceSet, Set<T> targetSet) { Set<T> set = new HashSet<T>(); int sourceSetSize = sourceSet.size(); int targetSetSize = targetSet.size(); Set<T> minSet = null; Set<T> maxSet = null; if (sourceSetSize <= targetSetSize) { minSet = sourceSet; maxSet = targetSet; } else { minSet = targetSet; maxSet = sourceSet; } for (T t : minSet) { if (maxSet.contains(t)) { set.add(t); } } return set; } }