List.contains() method in Salesforce

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

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