List.contains() method in Salesforce

Is there any specific reason why salesforce did not provide list.contains() method.

Edit 1: The below methods are added to List class and are available after Spring 18 release to Sandboxes and Production instances.

System.List Class

1) contains(listElement)
Returns true if the list contains the specified element.
2) indexOf(listElement)
Returns the index of the first occurrence of the specified element in this list. If this list does not contain the element, returns -1.

Link to official documentation



This is now a function you can use. It was implemented in the Spring 18 release.

I don’t know of an official reason “why,” but there’s an idea you can vote on. I’ll be sure to ask about it when I get a chance…

As I posted in that idea a few years ago, there’s a quick one-liner you can use that’s (relatively) faster than a straight loop, modified to be polymorphic:

Boolean listContains(Object[] source, Object target) {
    return (new Set<Object>(source)).contains(target);

Example uses in executeAnonymous:

Account a = new Account(Name='Test');
Account[] aList = new Account[] { a };
System.assert(listContains(aList, a));

Integer[] values = new Integer[] { 1, 1, 2, 3, 5 };
System.assert(listContains(values, 3));
System.assert(!listContains(values, 7));

Source : Link , Question Author : sunny , Answer Author : sfdcfox

Leave a Comment