Ints lastIndexOf() function in Java

Java 8Object Oriented ProgrammingProgramming

The lastIndexOf() method of the Ints class returns the index of the last appearance of the value target in array. The syntax is as follows −

public static int
lastIndexOf(int[] arr, int target)

Here, arr is the array of int values, whereas target is the int value for which we are finding the last index.

Let us first see an example −

Example

import com.google.common.primitives.Ints;
class Demo {
   public static void main(String[] args) {
      int[] myArr = { 10, 20, 30, 40, 50, 60,20, 80, 20, 100 };
      System.out.println(Ints.join("-", myArr));
      // finding last index of element 20
      int index = Ints.lastIndexOf(myArr, 20);
      if (index != -1) {
         System.out.println("The last index of element 20 = " + index);
      } else {
         System.out.println("The element 20 is not in the array.");
      }
   }
}

Output

10-20-30-40-50-60-20-80-20-100
The last index of element 20 = 8
raja
Published on 24-Sep-2019 07:36:34
Advertisements