Skip to main content

Find Index of Element in Salesforce List

·2 mins

A Salesforce list and map are super convenient ways of operating on a collection in Apex. Let’s say you magically have some collections but need to find (and probably change) one of the elements in the collection - here’s how you can do that.

First, let us create a list to play around with -

List<Integer> nums = new List<Integer>();
// (1, 2, 3)

We created a simple list nums with three integers. We can find out an element at a given index with -

System.debug('Element 0: ' + nums.get(0));
// 1

This was easy, but how do you inverse it and find the index of an element? Turns out that is easy too..

System.debug('Index for 3: ' + nums.indexOf(3));
// 2

The above method works for other simple types too..

list<string> cats = new list<string>{'joey','katy','blackadder','pirate'};
System.debug('Where is pirate? ' + cats.indexOf('pirate'));
// 3

How about something more complex? Here’s some code with list of lists and a way to find the index of a specified list -

List<List<string>> students = new List<List<string>>();
students.add(new List<string>{'Ram', 'John', 'Kit'});
students.add(new List<string>{'Zack', 'Mage', 'Joe'});
System.debug('students ' + students);
System.debug('Grade II Students: ' + students.indexOf(new List<string>{'Zack', 'Mage', 'Joe'}));
// 1

Not very practical, but works.

Let’s do one last thing. How can we get the index if we can do only partial matches?

For e.g. -

public class Student {
    public String Name {get; set;}
    public String Grade {get; set;}

List<Student> StudentList = new List<Student>();
Student stu1 = new Student();
stu1.Name = 'Ram';
stu1.Grade = 'I';
Student stu2 = new Student();
stu2.Name = 'John';
stu2.Grade = 'I';
StudentList.addAll(new List<Student>{stu1, stu2});

System.debug('StudentList: ' + StudentList);
// StudentList: (Student:[Grade=I, Name=Ram], Student:[Grade=I, Name=John])

We need to iterate through the list if we want to find a student by name in StudentList-

String findName = 'Ram';
for (Student st : StudentList) {
    if (st.Name == findName) {
        System.debug('Found ' + st);

While iterating through a list is easy, you might want to use a map if you find yourself doing the same key-based search repeatedly.