Experience Salesforce

Sets Initialization And Methods

What You’ll Learn

  • What Is Set Initialization In Apex?
  • Some Common Methods Of Set In Apex

What is Set Initialization in Apex?

In Salesforce Apex, initializing a Set can be done in several ways depending on whether you want the Set to be empty initially or pre-filled with values. The way you declare sets is similar to the way you declare lists. You can also have nested sets and sets of lists.

How to Initialize Set in Apex?

In Salesforce Apex, you can initialize a set in various ways. Here’s how you can do it:

// Empty set initialized
Set<String> strSet = new Set<String>();
// Set of List of Strings
Set<List<String>> set2 = new Set<List<String>>();

How to Use Set in Salesforce Apex?

Following are some common methods of set in Apex:

1add(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’)
2addAll(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’)
3clear()Removes all the elements.s.clear();s.addAll(l);
4clone()Makes duplicate of a set.List<String> s2 = s.clone();System.debug(s);//(‘abc’,’def’)
5contains(elm)Returns true if the set contains the specified element.Boolean result = s.contains(‘abc’);System.debug(result); // true
6containsAll(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
7size()Returns the size of set.System.debug(s.size()); // 2
8retainAll(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’)
9remove(elm)Removes the specified element from the set if it is present.s.add(‘ghi’);s.remove(‘ghi’);System.debug(s);//(‘abc’,’def’)
10removeAll(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’)

Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.