List.contains() method in Salesforce

2.9K    Asked by KanekoTakeda in Web-development , Asked on Jul 29, 2021
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) contains(listElement) Returns true if the list contains the specified element. ) 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.


Answered by Jack Russell

 Well, don’t know the official reason but why salesforce did not provide list.contains() method, but i guess, 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(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));


Your Answer

Interviews

Parent Categories