Remove element from linkedlist in java

Following methods are used to remove element from linkedlist in java:

  • remove(): It retrieves and removes the first element of the list.
  • remove(index): It removes the element at the specified position in the list.
  • remove(object): It removes the first occurrence of the specified element from the list, if it is present.
  • removeFirst(): It removes and returns the first element from the list.
  • removeFirstOccurrence(object): It removes the first occurrence of the specified element in the list (when traversing the list from head to tail).
  • removeLast(): It removes and returns the last element from the list.
  • removeLastOccurrence(object): It removes the last occurrence of the specified element in the list (when traversing the list from head to tail).

Example:

package com.w3schools;
 
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
	System.out.println("Actual LinkedList:"+linkedList);
	System.out.println("remov() method:"+linkedList.remove());
        System.out.println("After remove() method call:");
        System.out.println(linkedList);
        System.out.println("remove(index) method:"+linkedList.remove(2));
        System.out.println("After remove(index) method call:");
        System.out.println(linkedList);
        System.out.println("remov(object) method:"+linkedList.remove("Hemant"));
        System.out.println("After remove(object) method call:" + linkedList);
  }
}

Output

Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
remov() method:Jai
After remove() method call:
[Mahesh, Naren, Vivek, Vishal, Hemant]
remove(index) method:Vivek
After remove(index) method call:
[Mahesh, Naren, Vishal, Hemant]
remov(object) method:true
After remove(object) method call:[Mahesh, Naren, Vishal]