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

    Why the development team made specific design decisions is often exceedingly difficult or downright impossible to answer.

    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...

    @AdrianLarson Yeah thats true. But just wanted to check if members of community have any idea that they can share with others.

    You should post those updates as an answer rather than an update to your question.

  • sfdcfox

    sfdcfox Correct answer

    4 years ago

    Edit:

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

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used