Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
array
arrayutils
communitycreator

What is ArrayUtils.lastIndexOf in Java?

abhilash

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.

Syntax


public static int lastIndexOf(final int[] array, final int valueToFind)

Parameters

  • final int[] array: array of elements.

  • final int valueToFind the element to find.

Return value

The method returns the index of the last occurrence of the element, -1, if the element is not found in the array.

Add the Apache Commons-Lang package

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.


How to import ArrayUtils

You can import the ArrayUtils class as follows.


import org.apache.commons.lang3.ArrayUtils;

Code

Example 1

  • 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.

Example 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);

    }
}

Output


The index of the last occurrence of 2 is 8
The index of the last occurrence of -2 is -1

RELATED TAGS

java
array
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring