1

I have 2 sets s1 and s2 one condition is s1 > s2.
And my requirement is i can't make change in s1. and find difference of both set we can use another set to store result.

Set<String> s1 = new HashSet<String>();
s1.add("a");
s1.add("b");
s1.add("c");
s1.add("n");
s1.add("d");
Set<String> s2 = new HashSet<String>();
s2.add("b");
s2.add("d");
s2.add("c");

i want outpur like this
like s3= set1-set2
output :
s3=[a,n]

s1 and s2 both are huge set above 10000 elements and in loop. so i don't want to first copy s1 to s3 and then remove s2.

gifpif
  • 4,507
  • 4
  • 31
  • 45

2 Answers2

4

You can use this :

Set<String> s3 = new HashSet<String>();
for(String temp : s1){
    if(!s2.contains(temp)){
        s3.add(temp);
    }
}
for (String temp : s2) {
    if (!s1.contains(temp)) {
        s3.add(temp);
    }
}
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
3

Using Google Guava:

import com.google.common.collect.Sets;

Set<String> difference = Sets.difference(s1, s2);

Note, that Sets.difference is a lazy operation. It returns a view of the difference.

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155