Apex: convert from List to Set and vice versa

I can’t tell you how many times I have a method which has a Set as its parameter, and I’m working with a List, or vice versa. Of course, fundamentally the difference between Set and List is that Set is unordered and unique, whereas List is neither of these things.

Here’s the quickest and easiest way to convert from List to Set

List<String> listStrings = new List<String> {'a', 'a', 'b', 'c'};
Set<String> setString = new Set<String>(listStrings);
System.assertEquals(3, setString.size());

(in other words, use the Set constructor which takes List<X> as a parameter).

Here’s the quickest and easiest way to convert from Set to List

Set<String> setString = new Set<String> {'a', 'b', 'c'};
List<String> listStrings = new List<String>(setString);
System.assertEquals(3, listStrings.size());

(in other words, use the List constructor which takes Set<X> as a parameter).

There are other ways to do this, including using addAll, which you might want to do if you have an existing Collection, and you’re not just creating a new one. List and Set both have

listStrings.addAll(setString);

and

setString.addAll(listStrings);

respectively.

This entry was tagged , . Bookmark the permalink.