0

I am looking many of the queries on how to get intersection set of 2 sets in a efficent time. And looking for very efficient way. Before approching my own way why can not ask Java to build a method to perform the same. Why Java has not build a menthod like intersection on Collections class like sort method or somewhere in Collections? Any reason behind this?

Please consider this is a discussion on fit-falls of intersection on sets.

Thanks,

Chowdappa
  • 1,580
  • 1
  • 15
  • 31

1 Answers1

2

The closest you have to find intersection between 2 Collection is retainAll(). Note that retainAll doesn't returns a new Set containing intersection but rather modify the set instance on which it is called. For e.g. :

import java.util.HashSet;
import java.util.Set;

class Test2
 {

     public static void main(String[] args) {



         Set<String> set1 = new HashSet<>();
         set1.add("A");
         set1.add("B");

         Set<String> set2 = new HashSet<>();
         set2.add("A");
         set2.add("D");
         set1.retainAll(set2);
         System.out.println(set1);
     }

  }
sol4me
  • 15,233
  • 5
  • 34
  • 34