How to find the index of given element of a Java List?

Java 8Object Oriented ProgrammingProgramming

The indexOf(Object) method of the java.util.ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.

Example

 Live Demo

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<String> arrlist = new ArrayList<String>(5);
      arrlist.add("G");
      arrlist.add("E");
      arrlist.add("F");
      arrlist.add("M");
      System.out.println("Size of list: " + arrlist.size());
      for (String value : arrlist) {
         System.out.println("Value = " + value);
      }
      int retval=arrlist.indexOf("E");
      System.out.println("The element E is at index " + retval);
   }
}

Output

Size of list: 4
Value = G
Value = E
Value = F
Value = M
The element E is at index 1
raja
Published on 17-Jan-2018 10:55:10
Advertisements