A specific element in the LinkedList can be removed using the java.util.LinkedList.remove() method. This method removes the specified element the first time it occurs in the LinkedList and if the element is not in the LinkedList then no change occurs. The parameter required for the LinkedList.remove() method is the element to be removed.
A program that demonstrates this is given as follows.
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l); System.out.println("The element Mango is removed from the LinkedList? " + l.remove("Mango")); System.out.println("The LinkedList is: " + l); } }
The output of the above program is as follows
The LinkedList is: [Apple, Mango, Pear, Orange, Guava] The element Mango is removed from the LinkedList? true The LinkedList is: [Apple, Pear, Orange, Guava]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. After that, LinkedList.remove() method is used to remove the element “Mango” from the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows
LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l); System.out.println("The element Mango is removed from the LinkedList? " + l.remove("Mango")); System.out.println("The LinkedList is: " + l);