Write a Java program to Remove the given element from an ArrayList


This program removes specific elements from an ArrayList in Java. The ArrayList is created and initialized with several string values, and then two specific elements are removed using the remove() method. The first argument to the remove() method is the element to remove, which is specified as a string. The method removes the first occurrence of the element in the list. Finally, the modified list is printed to the console. This program demonstrates the flexibility of ArrayLists in Java, which allow for dynamic resizing and modification of the list at runtime.

Source Code

import java.util.ArrayList;
public class Remove_GivenElement
{
    public static void main(String[] args)
    {
		ArrayList<String> fru_list = new ArrayList<String>();
		fru_list.add("Pineapple"); 
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Guava");
		fru_list.add("Watermelon");
		System.out.println("Given ArrayList : "+fru_list);
 
		//Removing first occurrence of "Mulberry" 
		fru_list.remove("Mulberry");
 
		//Removing first occurrence of "Guava" 
		fru_list.remove("Guava");
 
		System.out.println("\nRemove the given Element from an ArrayList..");
		System.out.println(fru_list);
    }
}

Output

Given ArrayList : [Pineapple, Papaya, Mulberry, Apple, Banana, Cherry, Guava, Watermelon]

Remove the given Element from an ArrayList..
[Pineapple, Papaya, Apple, Banana, Cherry, Watermelon]

Example Programs