I want to find the union of several sets very efficiently because its time has an important effect on the full system.
Let's think our sets are like below:
s1 - 1, 2, 3, 4, 5, 6
s2 - 1, 2, 4, 8, 10, 12, 15, 18, 21
s3 - 1, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33
According to one solution:
They found the intersection of the sets beforehand.
s1, s2 (or s12) - 1, 2, 4
s1, s3 (or s13) - 1
s2, s3 (or s23) - 1
They have both individual sets and intersection sets when they need to compute the union of these 3 sets. So,
res1 = Sets.difference(s1, s12)
res1 = Sets.difference(res1, s13)
finalRes.addAll(res1)
res2 = Sets.difference(s2, s23)
finalRes.addAll(res2)
finalRes.addAll(s3)
Actually, I think this solution is efficient, but I wonder:
- Can we directly use Sets.union of guava, but it seems that the above solution is more efficient than this.
- Can we use a final set and for each element of each set we check this final set contains the element or not using contains method.
What do you suggest if we have 100 sets?