Skip to content

Java LinkedList Remove Elements Example

This example shows how to remove elements from the LinkedList in Java. This example also shows various methods to remove elements including remove, removeAll, and clear methods.

How to remove elements from LinkedList in Java?

There are several ways using which you can remove elements from the LinkedList as given below.

1. Remove an element using the remove method

To remove an element from the LinkedList object, use the remove method and pass the index of the element.

This method removes an element located at the specified index of the linked list object and returns the same.

Output

Note: If the specified index is out of the range, i.e. index is less than 0 or greater than or equal to the list size, the remove method throws IndexOutOfBoundsException exception.

There is an overloaded remove method that accepts the Object instead of the index.

This method removes the specified element from the list. It returns true if the element is found and removed from the list, false otherwise.

Output

Note: If the linked list contains objects of a custom class, the class must implement the equals and hashCode methods for these methods to work.

2. Removing the first and last elements

The removeFirst and removeLast methods delete the first and last element of the linked list respectively. Both of the methods return the element that was removed from the list.

Output

Since the LinkedList class is a linked list implementation in Java, it also supports poll operations. You can use the pollFirst and pollLast methods instead of the removeFirst and removeLast methods to remove first and last elements respectively.

You can also use the remove method without any arguments to remove the first or head element of the LinkedList object.

Output

3. Remove the first and the last occurrence of an element

The removeFirstOccurrence method of the LinkedList class removes the first occurrence of the element in the list.

Similarly, the removeLastOccurrence method removes the last occurrence of the element in the list.

Both of these methods return true if the element is found and is removed in the linked list, false otherwise.

Output

Note: If the linked list contains objects of a custom class, the class must implement the equals and hashCode methods for these methods to work.

4. Removing all elements

The clear method of the LinkedList class removes all elements from the LinkedList.

Output

Visit how to clear LinkedList example to know more.

This example is a part of the LinkedList in Java tutorial.

References:
Java 8 LinkedList

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.