lastIndexOf
is a static method of the ArrayUtils
class that finds the index of the last occurrence of an element in the array.
The method returns -1
if the element is not found in the array or if the passed array is null
.
public static int lastIndexOf(final int[] array, final int valueToFind)
final int[] array
: array of elements.
final int valueToFind
the element to find.
The method returns the index of the last occurrence of the element, -1
, if the element is not found in the array.
ArrayUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added to the Maven Project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
ArrayUtils
You can import the ArrayUtils
class as follows.
import org.apache.commons.lang3.ArrayUtils;
array = [1,2,3,4,5,2,3,2,2,4]
element = 2
The lastIndexOf
function returns 8
, i.e., the index of the last occurrence of the element 2
.
array = [1,2,3,4,5]
offset = -2
The lastIndexOf
function returns -1
, as the element is not found in the array.
import org.apache.commons.lang3.ArrayUtils; public class Main { public static void main(String[] args) { int[] array = {1,2,3,4,5,2,3,2,2,4}; int element = 2; int index = ArrayUtils.lastIndexOf(array, element); System.out.println("The index of the last occurrence of " + element + " is " + index); element = -2; index = ArrayUtils.lastIndexOf(array, element); System.out.println("The index of the last occurrence of " + element + " is " + index); } }
The index of the last occurrence of 2 is 8
The index of the last occurrence of -2 is -1
RELATED TAGS
CONTRIBUTOR
View all Courses