In the previous article we have discussed about Java ArrayList removeRange() Method with Example
In this article we are going to see the use of Java ArrayList lastIndexOf() method along with suitable examples.
Java ArrayList lastIndexOf() Method with Example
lastIndexOf():
This java.util.ArrayList.lastIndexOf()
method is used to get the last index position of the specified element in the ArrayList.
It returns the last index position of the specified element (if exist) else returns -1.
Syntax:
arrayListName.lastIndexOf()
Where,
arrayListName
refers to the name of your ArrayList.
Let’s see different examples to understand it more clearly.
Method-1: Java ArrayList lastIndexOf() Method – Example with String Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add string elements into the ArrayList using the
add()
method. - Display the ArrayList elements.
- Then find the last index of the specified element using
lastIndexOf()
method. - Print the index position.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a ArrayList of string datatype ArrayList<String> arr = new ArrayList<String>(); // Adding some elements to the ArrayList arr.add("book"); arr.add("copy"); arr.add("pen"); arr.add("book"); arr.add("pen"); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // get the position of Java occurred last System.out.println("Last Occurrence of book: " + arr.lastIndexOf("book")); System.out.println("Last Occurrence of notebook: " + arr.lastIndexOf("notebook")); } }
Output: The elements of ArrayList are: [book, copy, pen, book, pen] Last Occurrence of book: 3 Last Occurrence of notebook: -1
Method-2: Java ArrayList lastIndexOf() Method – Example with Integer Type ArrayList
Approach:
- Create a new ArrayList of type Integer.
- Add Integer elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Then find the last index of the specified element using
lastIndexOf()
method - Print the index position.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a ArrayList of string datatype ArrayList<Integer> arr = new ArrayList<Integer>(); // Adding some elements to the ArrayList arr.add(2); arr.add(52); arr.add(13); arr.add(17); arr.add(1); arr.add(2); arr.add(52); arr.add(13); arr.add(17); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // get the position of Java occurred last System.out.println("Last Occurrence of 2: " + arr.lastIndexOf(2)); System.out.println("Last Occurrence of 99: " + arr.lastIndexOf(99)); } }
Output: The elements of ArrayList are: [2, 52, 13, 17, 1, 2, 52, 13, 17] Last Occurrence of 2: 5 Last Occurrence of 99: -1
Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.
Related Java Programs: