15

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

  • 4
    Why the development team made specific design decisions is often exceedingly difficult or downright impossible to answer. – Adrian Larson May 2 '17 at 20:09
  • 4
    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... – sfdcfox May 2 '17 at 20:10
  • @AdrianLarson Yeah thats true. But just wanted to check if members of community have any idea that they can share with others. – sunny May 2 '17 at 20:13
  • You should post those updates as an answer rather than an update to your question. – Adrian Larson Dec 19 '17 at 22:04
22

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));
7

You can now use List.contains() with Spring 18 https://releasenotes.docs.salesforce.com/en-us/spring18/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.