beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java ArrayList lastIndexOf(Object 0bj) Method example

By Chaitanya Singh | Filed Under: Java Collections

The method lastIndexOf(Object obj) returns the index of last occurrence of the specified element in the ArrayList. It returns -1 if the specified element does not exist in the list.

public int lastIndexOf(Object obj)
This would return the index of last Occurrence of element Obj in the ArrayList.

Example

In the below example we have an Integer ArrayList which has few duplicate elements. We are fetching the last index of few elements using lastIndexof method.

package beginnersbook.com;
import java.util.ArrayList;
public class LastIndexOfExample {
  public static void main(String args[]) {
      //ArrayList of Integer Type
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(1);
      al.add(88);
      al.add(9);
      al.add(17);
      al.add(17);
      al.add(9);
      al.add(17);
      al.add(91);
      al.add(27);
      al.add(1);
      al.add(17);

      System.out.println("Last occurrence of element 1: "+al.lastIndexOf(1));
      System.out.println("Last occurrence of element 9: "+al.lastIndexOf(9));
      System.out.println("Last occurrence of element 17: "+al.lastIndexOf(17));
      System.out.println("Last occurrence of element 91: "+al.lastIndexOf(91));
      System.out.println("Last occurrence of element 88: "+al.lastIndexOf(88)); 
   }
}

Output:

Last occurrence of element 1: 9
Last occurrence of element 9: 5
Last occurrence of element 17: 10
Last occurrence of element 91: 7
Last occurrence of element 88: 1

Enjoyed this post? Try these related posts

  1. How to loop ArrayList in Java
  2. ArrayList in java with example programs – Collections Framework
  3. LinkedHashSet Class in Java with Example
  4. Java – Remove all elements from LinkedList example
  5. How to compare two ArrayList in Java
  6. Difference between list set and map in java?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

ArrayList Tutorial

  • Java ArrayList

Java ArrayList Methods

  • add(Object obj)
  • add(int index, Object element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • contains()
  • get()
  • indexOf()
  • ensureCapacity()
  • isEmpty()
  • lastIndexOf()
  • remove()
  • remove(Object obj)
  • trimToSize()
  • set()
  • clone()
  • clear()
  • size()

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap