Arraylist lastIndexOf() – Get last index of element in arraylist in Java

Learn how to get the index of last occurrence of a element in the ArrayList. We will be using ArrayList.lastIndexOf() method to get the last index.

1. ArrayList.lastIndexOf() method

This method returns the index of the last occurrence of the specified element in this list. It will return '-1' if the list does not contain the element.

1.1. lastIndexOf() method syntax

public int lastIndexOf(Object object) {
    if (o == null) {
        for (int i = size-1; i >= 0; i--)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = size-1; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

1.2. lastIndexOf() method parameter

object – the object which needs to be searched in the list for it’s last index position.

1.3. lastIndexOf() return value

Return value is of int type.

  • index – last index position of element if element is found.
  • -1 – if element is NOT found.

2. ArrayList lastIndexOf() example to get last index of element

Java program for how to get last index of arraylist. In this example, we are looking for last occurrence of string “alex” in the given list.

Note – Please note that arraylist index starts from 0.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles","alex","dough","gary","alex","harry"));
        
        int lastIndex = list.lastIndexOf("alex");
        
        System.out.println(lastIndex);

        lastIndex = list.lastIndexOf("hello");
        
        System.out.println(lastIndex);
    }
}

Program output.

6
-1

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.