

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the last occurrence of an element in a Java List?
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
- Related Questions & Answers
- Last occurrence of some element in a list in Python
- Find the last element of a list in scala
- How to find an element in a List with Java?
- How to get the last element of a list in Python?
- How to replace the last occurrence of an expression in a string in Python?
- Python How to get the last element of list
- Finding the last occurrence of a character in a String in Java
- How to find index of last occurrence of a substring in a string in Python?
- How to find the index of the last occurrence of repeated values in a vector in R?
- How to find the index of given element of a Java List?
- Get the substring before the last occurrence of a separator in Java
- How to get the second-to-last element of a list in Python?
- How do I find an element in Java List?
- How to get the last index of an occurrence of the specified value in a string in JavaScript?
- Search for an element matching the conditions and return the zero-based index of the last occurrence within the entire List in C#