removeFirst and removeLast in LinkedList
Apart from the usual remove() , remove(int index) and remove(Object o) we can use 4 other methods to remove elements from LinkedList.
The 4 methods are (details taken from LinkedList javaDoc)
1. removeFirst() – Removes and returns the first element from this list.
2. removeFirstOccurrence(Object o) – Removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
3. removeLast() – Removes and returns the last element from this list.
4. removeLastOccurrence(Object o) – Removes the last occurrence of the specified element in this list (when traversing the list from head to tail).
Example
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 39 40 41 42 43 | package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListMoreRemove { 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("Spring MVC"); linkedList.add("Hibernate"); linkedList.add("Oracle"); System.out.println("We have a Linked List with Elements::" + linkedList.toString()); // Lets use removeFirst(). This will remove "Java" linkedList.removeFirst(); // Lets use removeLast(). This will remove "Oracle" linkedList.removeLast(); // Lets use removeFirstOccurrence("Spring MVC"). We have 2 "Spring MVC" // in the list. removeFirstOccurrence() will remove the first // "Spring MVC" linkedList.removeFirstOccurrence("Spring MVC"); // Lets use removeLastOccurrence("Hibernate"). We have 2 "Hibernate" // in the list. removeLastOccurrence() will remove the last // "Hibernate" linkedList.removeLastOccurrence("Hibernate"); System.out.println("Now the Linked List has Elements::" + linkedList.toString()); } } |
Output
1 2 | We have a Linked List with Elements::[Java, JSP, Spring MVC, Hibernate, Spring MVC, Hibernate, Oracle] Now the Linked List has Elements::[JSP, Hibernate, Spring MVC] |