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

Possible Duplicate:
Efficiently finding the intersection of a variable number of sets of strings

Say, have two Hashset, how to calculate the intersection of them?

Set<String> s1 = new HashSet<String>();

Set<String> s2 = new HashSet<String>();

S1 INT S2 ?

This question is related to java set intersection hashset

The answer is


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 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 specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.


Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to set

java, get set methods golang why don't we have a set datastructure Simplest way to merge ES6 Maps/Sets? Swift Set to Array JavaScript Array to Set How to sort a HashSet? Python Set Comprehension How to get first item from a java.util.Set? Getting the difference between two sets Python convert set to string and vice versa

Examples related to intersection

How to calculate the intersection of two sets? Removing duplicates in the lists Intersect Two Lists in C# How can I get the intersection, union, and subset of arrays in Ruby? Intersection and union of ArrayLists in Java How to find list intersection? Simplest code for array intersection in javascript Find intersection of two nested lists?

Examples related to hashset

How to sort a HashSet? Does adding a duplicate value to a HashSet/HashMap replace the previous value How to Iterate over a Set/HashSet without an Iterator? How to calculate the intersection of two sets? Why there is no ConcurrentHashSet against ConcurrentHashMap Hashcode and Equals for Hashset Collection that allows only unique items in .NET? HashSet vs LinkedHashSet Define: What is a HashSet? Difference between HashSet and HashMap?