Java LinkedList Example

In this tutorial, we will explore the LinkedList class in Java, which is a part of the List interface. Unlike the ArrayList, LinkedList provides better performance for add and remove operations compared to random access operations. This tutorial will demonstrate how to use LinkedList with examples, covering all important operations and different ways for iteration using Java 8 features.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Step-by-Step Guide
    1. Creating a LinkedList
    2. Adding and Retrieving Elements
    3. Iterating Over the List
    4. Removing Elements
    5. LinkedList Methods
  4. Complete Code Example
  5. Conclusion

Introduction

LinkedList is a part of Java's java.util package and implements both the List and Deque interfaces. It provides a doubly-linked list data structure. LinkedList is useful in scenarios where frequent insertions and deletions are required. It offers methods to manipulate elements from both ends of the list.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed (latest version preferred)
  • An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse

Step-by-Step Guide

Step 1: Creating a LinkedList

First, let's create a LinkedList and add some elements to it.

import java.util.LinkedList;
import java.util.List;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Print the list
        System.out.println("LinkedList: " + linkedList);
    }
}

Output:

LinkedList: [Ravi, Sita, Arjun, Lakshmi]

Step 2: Adding and Retrieving Elements

Let's add some elements to the LinkedList and retrieve elements using different methods.

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Retrieve and print elements
        System.out.println("First element: " + linkedList.get(0));
        System.out.println("Second element: " + linkedList.get(1));
    }
}

Output:

First element: Ravi
Second element: Sita

Step 3: Iterating Over the List

We can iterate over the LinkedList using a for-each loop, iterator, and Java 8 features like forEach and streams.

Using For-Each Loop

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Iterate over the list using for-each loop
        System.out.println("Iterating over LinkedList using for-each loop:");
        for (String element : linkedList) {
            System.out.println(element);
        }
    }
}

Output:

Iterating over LinkedList using for-each loop:
Ravi
Sita
Arjun
Lakshmi

Using Iterator

import java.util.Iterator;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Iterate over the list using iterator
        System.out.println("Iterating over LinkedList using iterator:");
        Iterator<String> iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output:

Iterating over LinkedList using iterator:
Ravi
Sita
Arjun
Lakshmi

Using forEach and Lambda Expression (Java 8)

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Iterate over the list using forEach and lambda
        System.out.println("Iterating over LinkedList using forEach and lambda:");
        linkedList.forEach(element -> System.out.println(element));
    }
}

Output:

Iterating over LinkedList using forEach and lambda:
Ravi
Sita
Arjun
Lakshmi

Using Streams (Java 8)

import java.util.stream.Collectors;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Iterate over the list using streams
        System.out.println("Iterating over LinkedList using streams:");
        linkedList.stream().forEach(System.out::println);

        // Convert LinkedList to a List using streams
        System.out.println("LinkedList to List:");
        linkedList.stream().collect(Collectors.toList()).forEach(System.out::println);
    }
}

Output:

Iterating over LinkedList using streams:
Ravi
Sita
Arjun
Lakshmi
LinkedList to List:
Ravi
Sita
Arjun
Lakshmi

Step 4: Removing Elements

Let's remove elements from the LinkedList and demonstrate the use of remove method.

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Remove an element by index
        linkedList.remove(2);

        // Remove an element by value
        linkedList.remove("Lakshmi");

        // Print the list after removal
        System.out.println("LinkedList after removal: " + linkedList);
    }
}

Output:

LinkedList after removal: [Ravi, Sita]

Step 5: LinkedList Methods

Here are some other important methods provided by the LinkedList class:

  • addFirst(E e): Inserts the specified element at the beginning of this list.
  • addLast(E e): Appends the specified element to the end of this list.
  • removeFirst(): Removes and returns the first element from this list.
  • removeLast(): Removes and returns the last element from this list.
  • getFirst(): Returns the first element in this list.
  • getLast(): Returns the last element in this list.
import java.util.LinkedList;

public class LinkedListMethodsExample {
    public static void main(String[] args) {
        // Create a LinkedList
        LinkedList<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");

        // Add elements to the beginning and end of the list
        linkedList.addFirst("First");
        linkedList.addLast("Last");

        // Retrieve the first and last elements
        System.out.println("First element: " + linkedList.getFirst());
        System.out.println("Last element: " + linkedList.getLast());

        // Remove the first and last elements
        linkedList.removeFirst();
        linkedList.removeLast();

        // Print the list after removal
        System.out.println("LinkedList after removal: " + linkedList);
    }
}

Output:

First element: First
Last element: Last
LinkedList after removal: [Ravi, Sita]

Complete Code Example

Here's the complete code example demonstrating various operations with LinkedList:

import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList
        List<String> linkedList = new LinkedList<>();

        // Add elements to the list
        linkedList.add("Ravi");
        linkedList.add("Sita");
        linkedList.add("Arjun");
        linkedList.add("Lakshmi");

        // Retrieve and print elements
        System.out.println("First element: " + linkedList.get(0));
        System.out.println("Second element: " + linkedList.get(1));

       

       // Iterate over the list using for-each loop
        System.out.println("Iterating over LinkedList using for-each loop:");
        for (String element : linkedList) {
            System.out.println(element);
        }

        // Iterate over the list using iterator
        System.out.println("Iterating over LinkedList using iterator:");
        Iterator<String> iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate over the list using forEach and lambda
        System.out.println("Iterating over LinkedList using forEach and lambda:");
        linkedList.forEach(element -> System.out.println(element));

        // Iterate over the list using streams
        System.out.println("Iterating over LinkedList using streams:");
        linkedList.stream().forEach(System.out::println);

        // Convert LinkedList to a List using streams
        System.out.println("LinkedList to List:");
        linkedList.stream().collect(Collectors.toList()).forEach(System.out::println);

        // Remove an element by index
        linkedList.remove(2);

        // Remove an element by value
        linkedList.remove("Lakshmi");

        // Print the list after removal
        System.out.println("LinkedList after removal: " + linkedList);

        // Create a LinkedList
        LinkedList<String> linkedListMethods = new LinkedList<>();

        // Add elements to the list
        linkedListMethods.add("Ravi");
        linkedListMethods.add("Sita");

        // Add elements to the beginning and end of the list
        linkedListMethods.addFirst("First");
        linkedListMethods.addLast("Last");

        // Retrieve the first and last elements
        System.out.println("First element: " + linkedListMethods.getFirst());
        System.out.println("Last element: " + linkedListMethods.getLast());

        // Remove the first and last elements
        linkedListMethods.removeFirst();
        linkedListMethods.removeLast();

        // Print the list after removal
        System.out.println("LinkedList after removal: " + linkedListMethods);
    }
}

Output:

First element: Ravi
Second element: Sita
Iterating over LinkedList using for-each loop:
Ravi
Sita
Arjun
Lakshmi
Iterating over LinkedList using iterator:
Ravi
Sita
Arjun
Lakshmi
Iterating over LinkedList using forEach and lambda:
Ravi
Sita
Arjun
Lakshmi
Iterating over LinkedList using streams:
Ravi
Sita
Arjun
Lakshmi
LinkedList to List:
Ravi
Sita
Arjun
Lakshmi
LinkedList after removal: [Ravi, Sita]
First element: First
Last element: Last
LinkedList after removal: [Ravi, Sita]

Conclusion

In this tutorial, we demonstrated how to use the LinkedList class in Java. We covered creating a LinkedList, adding and retrieving elements, iterating over the list using various methods, removing elements, and using some important LinkedList methods. By following this guide, developers can effectively use LinkedList in scenarios where frequent insertions and deletions are required.

Comments