Does Apex List have indexOf method?

As you can see from the List Instance Methods page, that is not currently supported. You could fake it by using maps, which do have that feature, containsKey(Object). Place either your key field (id field or external id if using sObjects) or just put your entire object into the key, if it is small enough and you aren't worried about heap size.

Examples:

 Map<id, Lead> myLeads = new Map<id, Lead>();
 System.debug(myLeads.containsKey(someId));
 Map<string, string> lastNames = new Map<string, string>();
 System.debug(lastNames.containsKey('Smith'));

Or, as the Idea you linked to pointed out, you could use Sets, instead. Sets have a contains(Object) method that would accomplish the same thing.


There is no method for doing what you want, the only way to find the index of a specific item would be to run through the list and check each value. Since the list doesn't use a hash internally, even if it did support this method it'd just be doing the same and with the recent change to CPU time over script statements you should be perfectly fine unless we're talking about millions of items!


I just wanted to provide an updated answer to this for anybody who visits this question in 2018 & beyond and mention that the upcoming version of Salesforce (Spring '18) does add the indexOf() method to List: Spring '18 Release Notes: New and Changed Classes

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.

Tags:

Apex