Write a Java program to get the position of a particular element in an ArrayList


The program defines a class GetPosition_ParticularEle that contains a main method. In the main method, an ArrayList of type String named fru_list is created and initialized with some values.

The program then uses the indexOf and lastIndexOf methods of the ArrayList class to find the position of specific elements in the list.

The indexOf method is used to find the first occurrence of an element in the list, and the lastIndexOf method is used to find the last occurrence of an element in the list.

Source Code

import java.util.ArrayList;
public class GetPosition_ParticularEle
{
    public static void main(String[] args)
    {
		ArrayList<String> fru_list = new ArrayList<String>();
		fru_list.add("Pineapple"); 
		fru_list.add("Papaya");
		fru_list.add("Mango");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		System.out.println("Given ArrayList : "+fru_list); 
 
		System.out.println("Watermelon Element Index of : "+fru_list.indexOf("Watermelon")); 
		System.out.println("Pineapple Element Index of : "+fru_list.lastIndexOf("Pineapple"));
		System.out.println("Apple Element Index of : "+fru_list.lastIndexOf("Apple"));
    }
}

Output

Given ArrayList : [Pineapple, Papaya, Mango, Apple, Banana, Cherry, Watermelon]
Watermelon Element Index of : 6
Pineapple Element Index of : 0
Apple Element Index of : 3

Example Programs