How to find the last occurrence of an element in a Java List?

JavaObject Oriented ProgrammingProgramming

Java List provides a method lastIndexOf() which can be used to get the last location of an element in the list.

int lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Parameters

  • o − Element to search for.

Returns

The index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Throws

  • ClassCastException − If the type of the specified element is incompatible with this list (optional).

  • NullPointerException − If the specified element is null and this list does not permit null elements (optional).

Example

Following is the example showing the usage of lastIndexOf() method to get the last occurrence of an element.

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 4));
      System.out.println("List: " + list);
      System.out.println("4 is present at: " + list.lastIndexOf(Integer.valueOf(4)));
      System.out.println("9 is present at: " + list.lastIndexOf(Integer.valueOf(9)));
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 4, 5, 6, 7, 8, 4]
4 is present at: 8
9 is present at: -1
raja
Updated on 09-May-2022 12:25:12

Advertisements