How to remove elements from LinkedList
In this post we will see methods on how to remove elements from LinkedList.
We will see example using
remove() ,
remove(int index) and
remove(Object o)
Note that index parameter starts from 0. So if you want to remove element from the 2nd position then index will be 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListRemoveElement { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("Java"); linkedList.add("JSP"); linkedList.add("Spring MVC"); linkedList.add("Hibernate"); linkedList.add("Oracle"); linkedList.add("JQuery"); System.out.println("We have a Linked List with Below Elements::" + linkedList.toString()); // Use remove() method - This will remove the element at index 0 - // "Java" linkedList.remove(); // Use remove(index) method to remove 3rd element. // Since the linkedList now has // "JSP, Spring MVC, Hibernate, Oracle, JQuery" // element at index 2 - "Hibernate" will be removed. linkedList.remove(2); // Use remove(object) method to remove element "Sixth Element" linkedList.remove("Sixth Element"); // After using remove methods final linked list System.out.println("After using remove methods final linked list::" + linkedList.toString()); } } |
Output
1 2 | We have a Linked List with Below Elements::[Java, JSP, Spring MVC, Hibernate, Oracle, JQuery] After using remove methods final linked list::[JSP, Spring MVC, Oracle, JQuery] |
We can remove elements from Linked List using removeFirst(), removeLast(), removeFirstOccurrence() and removeLastOccurrence() methods as well.
You can get more details here – removeFirst(), removeLast(), removeFirstOccurrence() and removeLastOccurrence() methods in LinkedList