How to calculate the intersection of two sets?

Use the retainAll() method of Set: If you want to preserve the sets, create a new set to hold the intersection: The javadoc of retainAll() says it’s exactly what you want: Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the … Read more

Removing duplicates in lists

The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function. The following example should cover whatever you … Read more