Java Collection How to - Search element for Position








Question

We would like to know how to search element for Position.

Answer

  
public int indexOf(Object element)
public int lastIndexOf(Object element)
  
  

return -1 if the element is not found.

To find all of the positions for a single element in an ArrayList, you'll need to convert the list to a Vector and use the versions of indexOf() or lastIndexOf().

import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    System.out.println(list.lastIndexOf("A"));
  }
}

The code above generates the following result.