How to calculate the intersection of two sets? [duplicate]

Use the retainAll() method of Set: Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both sets If you want to preserve the sets, create a new set to hold the intersection: Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2); The javadoc of retainAll() says it’s exactly what you … Read more

Intersection and union of ArrayLists in Java

Here’s a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don’t modify the original lists input to the methods. public class Test { public static void main(String… args) throws Exception { List<String> list1 = new ArrayList<String>(Arrays.asList(“A”, “B”, “C”)); List<String> list2 = new ArrayList<String>(Arrays.asList(“B”, “C”, “D”, … Read more