2

This is a logic I am stuck with. I have two sets. One set has about 20k records(Set A). Another one has about 5 records(Set B). Set B is a subset of set A. What I want to do is put the common values of the two sets in any one of the sets. I have to do it without using any kind of loop. Any help would be really appreciated

2
  • retainAll can do the magic
    – kurunve
    Jun 24, 2017 at 7:31
  • @kurunve You should add an answer instead of a comment.
    – sfdcfox
    Jun 24, 2017 at 7:41

1 Answer 1

5

There is a standard Set method, called retainAll.

That method remove all elements in original set, except from set in parameter (save in current set intersection of the two sets) and returns true if original set has been changed during operation. For example:

Set<Integer> s1 = new Set<Integer>{1,2,3};
Set<Integer> s2 = new Set<Integer>{3,4,2}

Boolean result = s1.retainAll(s2);

In that case, result will be true, and s1 will contains 2 and 3 only.

Documentation here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .