Intersecting Two Lists/Sets in Java
If you have two collections of objects, sometimes you want to find the intersection of those collections. This means finding only those items that overlap between the two collections. This is straightforward to do in Java.
import java.util.*; public static Set Intersect(Set set1, Set set2) { Set intersection = new HashSet(set1); intersection.retainAll(new HashSet(set2)); return intersection; } Set set1 = new HashSet(); set1.add("abc"); set1.add("def"); Set set2 = new HashSet(); set2.add("def"); set2.add("ghi"); for (Object item : Intersect(set1, set2)) System.out.println(item);
This would output: “def”
You can generalize this to work with any collection using the following:
public static Collection Intersect(Collection coll1, Collection coll2) { Set intersection = new HashSet(coll1); intersection.retainAll(new HashSet(coll2)); return intersection; }
So then you could use something like an ArrayList.
ArrayList list1 = new ArrayList(); list1.add("abc"); list1.add("def"); ArrayList list2 = new ArrayList(); list2.add("def"); list2.add("ghi"); for (Object item : Intersect(list1, list2)) System.out.println(item);
See also the post on finding the union of two collections.