By user496949

2012-01-16 15:23:40 8 Comments

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 ?


@Emmanuel N 2012-01-16 15:26:20

Yes there is retainAll check out this

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

@Bohemian 2012-01-16 15:25:45

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

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.

@Allison 2018-01-17 09:54:30

Just a note for anyone looking to use retainAll on another Collection, such as a list with duplicate elements. Depending on the contents of the collection you can throw an UnsupportedOperationException, and it also won't filter frequencies correctly (it retains any and all occurrences of a value in the left multiset, regardless of how many times it occurs in the right multiset).

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) is giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 629597 View
  • 6601 Score
  • 10 Answer
  • Tags:   java date timezone

59 Answered Questions

[SOLVED] How can I concatenate two arrays in Java?

41 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

17 Answered Questions

[SOLVED] How to convert an Array to a Set in Java

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3904419 View
  • 3361 Score
  • 65 Answer
  • Tags:   java random integer

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

7 Answered Questions

[SOLVED] How to join two sets in one line without using "|"

  • 2013-07-02 15:05:51
  • fandyst
  • 226856 View
  • 142 Score
  • 7 Answer
  • Tags:   python set

19 Answered Questions

[SOLVED] Find intersection of two nested lists?

26 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 1057392 View
  • 1885 Score
  • 26 Answer
  • Tags:   java enums

Sponsored Content