Apex Updates: New List Tricks

Chris Stegall
creme de la crm
Published in
2 min readApr 9, 2019

Today’s post covers an Apex update that will make even the sternest Salesforce dev crack a smile — the addition of some much-asked-for list methods!

For years, lists presented a bit of a challenge in Apex because, unlike Java or C#, there was no code-succinct way to check a list’s contents. There were IdeaExchange suggestions, creative work-arounds, and no shortage of searches from other devs looking for answers.

The most common kludge involved defining a set, adding all of the list elements to the set, and then using the Set.contains() method to check for the element and in that way, figure out if the desired item is in your list.

Until the Spring ’18 Release, that is! Among a bunch of awesome upgrades was a huge improvement to list functionality giving devs everywhere the tools they’ve been asking for for years.

Let’s dive in!

contains(listElement)

First, and probably most exciting, is lists getting their very own contains method!

Now checking if a list contains the item you’re looking for is as easy as contains(listElement) ! It’ll return true if the list contains the element, and false if it doesn’t. Fast, easy, and a whole heap more brief than any creative workarounds using sets, maps, or other methods.

indexOf(listElement)

Lists also picked up their own index method, so devs can quickly determine where an element is in any given list.

Simply add a indexOf(listElement) and it’ll return the position of the first occurrence of the specified list element (as an integer) and, if the list doesn’t contain the element, it’ll return a -1!

So clean up your code and say goodbye to that spaghetti! You can see all of the Apex class updates from Spring ’18 right here and, if you still need a hand turning your vision into functioning code, give us a call! Our dev team is one of the best in the business and we’ve helped over 1,000 orgs build the functionality they need to make Salesforce “just work”.

In the meantime, keep working hard, smart, and happy — and we’ll see you in the cloud.

--

--

Chris Stegall
creme de la crm

Digital Marketing Director @ MK Partners. Salesforce lover, user, and constant learner.