The way you declare sets is similar to the way you declare lists. You can also have nested sets and sets of lists.

Ex:

// Empty set initialized

Set<String> strSet = new Set<String>();

// Set of List of Strings

Set<List<String>> set2 = new Set<List<String>>();

Some common methods of set:

add(element)Adds an element to set and only takes the argument of special datatype while declaring the set.Set<String> s = new Set<String>();
s.add(‘abc’);
s.add(‘ABC’);
s.add(‘abc’);
System.debug(s);//(‘abc’,’ABC’)
addAll(list/set)Adds all of the elements in the specified list/set to the set if they are not already present.List<String> l = new List<String>();
l.add(‘abc’);
l.add(‘def’);
s.addAll(l);
System.debug(s);//(‘abc’,’ABC’,’def’)
clear()Removes all the elements.s.clear();
s.addAll(l);
clone()Makes duplicate of a set.List<String> s2 = s.clone();
System.debug(s);//(‘abc’,’def’)
contains(elm)Returns true if the set contains the specified element.Boolean result = s.contains(‘abc’);
System.debug(result); // true
containsAll(list)Returns true if the set contains all of the elements in the specified list. The list must be of the same type as the set that calls the method.Boolean result = s.containsAll(l);
System.debug(result); // true
size()Returns the size of set.System.debug(s.size()); // 2
retainAll(list)Retains only the elements in this set that are contained in the specified list and removes all other elements.s.add(‘ghi’);
System.debug(s);//(‘abc’,’def’,’ghi’)
s.retainAll(l);
System.debug(s);//(‘abc’,’def’)
remove(elm)Removes the specified element from the set if it is present.s.add(‘ghi’);
s.remove(‘ghi’);
System.debug(s);//(‘abc’,’def’)
removeAll(list)Removes the elements in the specified list from the set if they are present.s.add(‘ghi’);
s.removeAll(l);
System.debug(s);//(‘ghi’)

Our Recent Blog

Share This Post