How to remove an item in the Linked List in Java (Android Studio) – IT Blog
IT Blog
Boris IT Expert

How to remove an item in the Linked List in Java (Android Studio)

Boris~October 24, 2020 /Linked List

Remove an item from the Linked List by using object of collections in Java, you may call several methods:

  1. Remove element by value
linkedList.remove(2);
Remove element from linked list in java by index

2. Remove first element in the Linked List

linkedList.removeFirst();
Remove first element from linked list in java

3. Remove last element in the Linked List

linkedList.removeLast();
Remove last element from linked list in java

Removing the element from Linked List in Java without collections.

If you are using your implementation with model and constructor, there is another way to remove items by a key. An example of how to develop and implement LinkedList in java, you can check on this page. It might be useful to know because it is one of the common questions in technical interviews. 

private void removeTheItemFromTheListByKey() {
        //You need to create linked list first       
        creatingLinkedList();
 
        //Put out selection to the start of the list
        ListNode selectedItem = head;

        //Temporary node to track item to be attached with
        ListNode temporaryNode = null;
 
        //The value we are looking for
        int searchedValue = 122;
 
        //In case first item is item we are looking for we just remove it by moving head to the next item
        if (selectedItem != null && selectedItem.data == searchedValue) {
            head = selectedItem.next;
            return;
        }
 
        //We are going through the loop until we find the item with needed value and then go out
        while (selectedItem != null && selectedItem.data != searchedValue) {

            //Moving temporary item to next if item not found yet
            temporaryNode = selectedItem;
            //Moving selected item to compare searched key with data of the item
            selectedItem = selectedItem.next;
        }
 

        //We have found the item with the need value and connecting temporary item to the next item after selected
        //So removing selected item between them
        temporaryNode.next = selectedItem.next;
 
        //Going back to the head to log the list
        selectedItem = head;
        while (selectedItem != null) {
            //Showing data of each item in the logs
            Log.d("linkedList", "-> " + selectedItem.data);

            selectedItem = selectedItem.next;
        }
        Log.d("linkedList", "-> " + null);
    }

In this article, you figured out how to remove an element from a linked list in java on an example of two scenarios. With the help of the Java collections and in case of implementation via constructor and model class.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!