How do I remove an item from LinkedList?

This program shows you how to use the remove(int index) method of LinkedList class to remove an item at specified index from linked list object.

package org.kodejava.example.util;

import java.util.LinkedList;

public class LinkedListRemove {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        System.out.println("Original values are:");
        System.out.println("====================");
        for (String name : names) {
            System.out.println("Name = " + name);
        }

        // Remove Carol from the linked list.
        names.remove(2);

        System.out.println("New values are:");
        System.out.println("====================");
        for (String name : names) {
            System.out.println("Name = " + name);
        }
    }
}

The result of the program above are:

Original values are:
====================
Name = Alice
Name = Bob
Name = Carol
Name = Mallory
New values are:
====================
Name = Alice
Name = Bob
Name = Mallory

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.