-1

Is easy way to get the intersection of two sets? I have:

    Set<Long> set1 = {1,2,3}
    Set<Long> set2 = {2,3,4}

And I looking or method like:

    Set<Long> intersection = new HashSet<>();
    intersection.intersect(set1, set2);

And intersection.toString() produce me set contains {2,3}

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
Kacper
  • 1,000
  • 2
  • 10
  • 18
  • 2
    Use `set1.retainAll(set2)` – Eran Jul 14 '15 at 09:06
  • If you don't mind to use apache commons. Here you are: https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/CollectionUtils.html#intersection(java.util.Collection, java.util.Collection) util method is called intersection – Mirek Surma Jul 14 '15 at 09:08

4 Answers4

3

You can use retainAll().

Note that this will modify one of the collections so you might want to create a copy first.

xp500
  • 1,426
  • 7
  • 11
2

Use the retainAll() method of Set

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

But, retainAll, will modify the content of s1. You should create a copy of s1 and use retainAll on the copy

Avoid this by below,

Set<String> mySet = new HashSet<String>(s1); // use the copy constructor
mySet.retainAll(s2);
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

Or to preserve the values:

Set<String> intersection = new HashSet<String>(set1);
intersection.retainAll(set2);
VWeber
  • 1,261
  • 2
  • 12
  • 34
1

The retainAll() method is used to remove it's elements from a list that are not contained in the specified collection.

Set<Long> set1 = {1,2,3}
Set<Long> set2 = {2,3,4}    
set1.retainAll(set2);//finally prints 2,3
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31