9

I need to find the index of an element in a List, similar to indexOf method provided by Java API.

My current solution is to iterate over the list to find the index myself. I just wonder if there's another way to perform this task since it is quite basic.

I am aware of this discussion: https://success.salesforce.com/ideaView?id=08730000000b9RZAAY

I wonder if there's any update since the post was a year ago (as of October 2013).

6

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.

3
  • 3
    Sorta offtopic, but am I crazy or has the apex & vf documentation been reformatted recently into a much less usable format?
    – Phil Rymek
    Oct 29 '13 at 22:41
  • Thanks, @Mike! However, your answer is kind of off topic. I didn't ask about contains. If I were to use Map, the index would be messed up because Map uses HashCode to order sObjects.
    – Mingyu
    Oct 29 '13 at 22:44
  • I think Mike has answered the question by saying it is not supported but you can at least use a Map or a Set to determine in a single method call if the List contains the element in question, saving you from iterating over the list when the list does not contain the element e.g. indexOf(stuff) == -1.
    – Phil Rymek
    Oct 29 '13 at 22:53
4

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!

3

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.

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.