Java LinkedList Tutorial With Examples

Introduction to Java LinkedList class

Java LinkedList class is the implementation class of List interface. It uses a doubly linked list as its underlying data structure.

Linked List data structure is a linear data structure. In this data structure, elements are not stored in contiguous memory locations and each element isΒ  stored as a separate object which contains : a data part and address part.Β Each element in LinkedList is known as a node.

Important points to remember about Java LinkedList are:

  • Java LinkedList class maintains the insertion order of elements.
  • We can store duplicate elements in Java LinkedList.
  • We can store null value in Java LinkedList.
  • Java LinkedList class is an non synchronized collection class hence it is not thread-safe.
  • Java LinkedList class is preferred over ArrayList, as manipulation in LinkedList isΒ  fast because no shifting is required while manipulating elements.
  • Java LinkedList class can be used not only as a list but stack and queue as well.

Hierarchy of Java LinkedList class

Java LinkedList class inherits the AbstractList class and implements List and Deque interfaces.

Java LinkedList

Java LinkedList representation

Java LinkedList

Constructors of Java LinkedList class

Constructor Description
LinkedList() The default constructor of Java LinkedList can be used to construct an empty list.
LinkedList(Collection<? extends E> c) This parameterized constructor of Java LinkedList can be used to construct a list which will contain the elements of the specified collection (c), the order will be same as returned by the collection’s iterator.

Methods of Java LinkedList class

Method Description
boolean add(E e) This method is used to append/add the specified element (e) to end of the list.
void add(int index, E element) This method is used to insert the specified element at the specified index/position in the list.
boolean addAll(Collection<? extends E> c) This method is used to append all the elements of the specified collection (c) to the end of this list, the order will be same as returned by the specified collection’s iterator.
boolean addAll(int index, Collection<? extends E> c) This method is used to append all the elements of the specified collection (c) , starting at the specified position (index) of the list.
void addFirst(E e) This method is used to insert the given element (e) at the beginning of the list.
void addLast(E e) This method is used to append / add the given element (e) to the end of a list.
void clear() This method is used to remove all the elements from the list.
Object clone() This method will return the shallow copy of an ArrayList.
boolean contains(Object o) This method will return true if a list contains a specified element and false in case of vice versa.
Iterator<E> descendingIterator() This method is used to return an iterator over the elements in a deque in reverse sequential order.
E element() This methodΒ is used to retrieve and return the first element of the list.
E get(int index) This method is used to return the element from the specified position of a list.
E getFirst() This method is used to return the first element of a list.
E getLast() This methodΒ is used to return the last element of a list.
int indexOf(Object o) This method is used to return the index in a list of the first occurrence of the specified element and -1 if the list does not contain any element.
int lastIndexOf(Object o) This method is used to return the index in a list of the last occurrence of the specified element and -1 if the list does not contain any element.
ListIterator<E> listIterator(int index) This method is used to return a list-iterator of the elements in proper sequence, starting at the specified position/index in the list.
boolean offer(E e) This method adds the specified element as the last element of a list.
boolean offerFirst(E e) This methodΒ inserts the specified element at the front/beginning of a list.
boolean offerLast(E e) This method inserts the specified element at the end of a list.
E peek() This methodΒ retrieves and returns the first element of a list.
E peekFirst() This method retrieves the first element of a list or returns null if the list does not have any elements.
E peekLast() This method retrieves and returns the last element of a list or returns null if the list does not have any elements.
E poll() This method retrieves and removes the first element of a list.
E pollFirst() This method retrieves and removes the first element of a list, or returns null if the list is empty.
E pollLast() This methodΒ retrieves and removes the last element of a list, or returns null if the list does not have any elements.
E pop() This methodΒ pops/delete an element from the stack represented by the invoking list.
void push(E e) This methodΒ pushes/inserts an element onto the stack represented by the invoking list.
E remove() This methodΒ is used to retrieve and removes the first element of a list.
E remove(int index) This methodΒ is used to remove the element at the specified position in a list.
boolean remove(Object o) This methodΒ is used to remove the first occurrence of the specified element in a list.
E removeFirst() This methodΒ removes/deletes and returns the first element from the invoking list.
boolean removeFirstOccurrence(Object o) This methodΒ is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).
E removeLast() This methodΒ removes/deletes and returns the last element from the invoking list.
boolean removeLastOccurrence(Object o) This methodΒ removes the last occurrence of the specified element in a list (when traversing the list from head to tail).
E set(int index, E element) This methodΒ replaces the element at the specified position in a list with the specified element.
Object[] toArray() This methodΒ is used to return an array containing all the elements in a list in proper sequence (from first to the last element).
<T> T[] toArray(T[] a) This methodΒ returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.
int size() This methodΒ is used to return the number of elements in a list.

Example 1: Create a LinkedList and add new elements to it

Following example illustrates, How to :

  1. Create a LinkedList.
  2. Add new elements to the LinkedList.
  3. Use of add() method of Java LinkedList.
  4. Use of addFirst() method of Java LinkedList.
  5. Use of addLast() method of Java LinkedList.
  6. Add existing collection to the LinkedList using addAll() method.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class CreateLinkedList {
public static void main(String[] args) {

// Creating a new LinkedList
LinkedList<String> names = new LinkedList<>();

// Addition of new elements to the end of the LinkedList using add() method.
names.add("Katrina");
names.add("Varun");
names.add("Priyanka");
names.add("Arjun Kapoor");
names.add("Salman");

System.out.println("Initial LinkedList : " + names);

// Addition of element at the specified position in the LinkedList
names.add(2, "Deepika");
System.out.println("After add(2, \"Deepika\") : " + names);

// Addition of element at the beginning of the LinkedList
names.addFirst("John");
System.out.println("After addFirst(\"John\") : " + names);

// Addition of element at the end of the LinkedList , Note : This method is equivalent to the 
// add() method
names.addLast("Salman Khan");
System.out.println("After addLast(\"Salman Khan\") : " + names);

// Addition of all the elements from an existing collection to the end of LinkedList
List<String> celebrity = new ArrayList<>();
celebrity.add("Sonakshi");
celebrity.add("Alia");

names.addAll(celebrity);
System.out.println("After addAll(celebrity) : " + names);
}
}

Output :

Initial LinkedList : [Katrina, Varun, Priyanka, Arjun Kapoor, Salman]
After add(2, "Deepika") : [Katrina, Varun, Deepika, Priyanka, Arjun Kapoor, Salman]
After addFirst("John") : [John, Katrina, Varun, Deepika, Priyanka, Arjun Kapoor, Salman]
After addLast("Salman Khan") : [John, Katrina, Varun, Deepika, Priyanka, Arjun Kapoor, Salman, Salman Khan]
After addAll(celebrity) : [John, Katrina, Varun, Deepika, Priyanka, Arjun Kapoor, Salman, Salman Khan, Sonakshi, Alia]

Example 2: Retrieve elements from Java LinkedList

Following example illustrates, How to :

  1. retrieve the first element in the LinkedList.
  2. retrieve the last element in the LinkedList.
  3. retrieve the element at a given index in the LinkedList.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class RetrieveFromLinkedList {
public static void main(String[] args) {

// Creating a new LinkedList
LinkedList<String> names = new LinkedList<>();

// Addition of new elements to the end of the LinkedList using add() method.
names.add("Katrina");
names.add("Varun");
names.add("Priyanka");
names.add("Arjun Kapoor");
names.add("Salman");

// Retrieving the first element in the LinkedList using getFirst()
// Please note : The getFirst() method throws NoSuchElementException if the LinkedList is empty

String firstElement = names.getFirst();
System.out.println("First Element : " + firstElement);

// Retrieving the last element in the LinkedList using getLast()
// Please note : The getLast() method throws NoSuchElementException if the LinkedList is empty
String lastElement = names.getLast();
System.out.println("Last Element : " + lastElement);

// Retrieving the element from a given position in the LinkedList
String name = names.get(2);
System.out.println("Element present at position 2 : " + name);

}
}

Output :

First Element : Katrina
Last Element : Salman
Element present at position 2 : Priyanka

Example 3: Remove elements from Java LinkedList

Following example illustrates, How to :

  1. Remove the first element from the LinkedList.
  2. Remove the last element from the LinkedList.
  3. Remove the first occurrence of a given element from the LinkedList.
  4. Remove all the elements that satisfy a given predicate from the LinkedList.
  5. Remove all the elements from LinkedList.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class RemoveFromLinkedList {
public static void main(String[] args) {

// Creating a new LinkedList
LinkedList<String> names = new LinkedList<>();

// Addition of new elements to the end of the LinkedList using add() method.
names.add("Katrina");
names.add("Varun");
names.add("Priyanka");
names.add("Arjun Kapoor");
names.add("Salman");
names.add("Priyanka");
names.add("SRK");

System.out.println("Initial LinkedList :: " + names);

// Removing the first element from the LinkedList
// Please note : This method Throws NoSuchElementException if the LinkedList is empty
String element = names.removeFirst(); 
System.out.println("After removing the first element " + element + " => " + names);

// Removing the last element from the LinkedList
// Please note : This method Throws NoSuchElementException if the LinkedList is empty
element = names.removeLast(); 
System.out.println("After removing the last element " + element + " => " + names);

// Removing the first occurrence of the specified element from the LinkedList
boolean isRemoved = names.remove("Priyanka");
if(isRemoved) {
System.out.println("Removed Priyanka => " + names);
}

// Removing all the elements that satisfy the given predicate
names.removeIf(name -> name.startsWith("S"));
System.out.println("After removing elements starting with S => " + names);

// Clear the LinkedList by removing all of its elements
names.clear();
System.out.println("Cleared the LinkedList :: " + names);

}
}

Output :

Initial LinkedList :: [Katrina, Varun, Priyanka, Arjun Kapoor, Salman, Priyanka, SRK]
After removing the first element Katrina => [Varun, Priyanka, Arjun Kapoor, Salman, Priyanka, SRK]
After removing the last element SRK => [Varun, Priyanka, Arjun Kapoor, Salman, Priyanka]
Removed Priyanka => [Varun, Arjun Kapoor, Salman, Priyanka]
After removing elements starting with S => [Varun, Arjun Kapoor, Priyanka]
Cleared the LinkedList :: []

Example 4: Searching elements in Java LinkedList

Following example illustrates, How to :

  1. Check if an element exists in a LinkedList or not.
  2. Find the index of the first occurrence of an element in the LinkedList.
  3. Find the index of the last occurrence of an element in the LinkedList.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class SearchInLinkedList {
public static void main(String[] args) {

// Creating a new LinkedList
LinkedList<String> names = new LinkedList<>();

// Addition of new elements to the end of the LinkedList using add() method.
names.add("Katrina");
names.add("Varun");
names.add("Priyanka");
names.add("Arjun Kapoor");
names.add("Salman");
names.add("Priyanka");
names.add("SRK");

// Checking if the LinkedList contains an element or not
System.out.println("Does Names LinkedList contains \"Salman\"? : " + names.contains("Salman"));

// Finding the index of the first occurrence of an element in the LinkedList
System.out.println("indexOf \"Priyanka\" : " + names.indexOf("Priyanka"));
System.out.println("indexOf \"John\" : " + names.indexOf("John"));

// Finding the index of the last occurrence of an element in the LinkedList
System.out.println("lastIndexOf \"Priyanka\" : " + names.lastIndexOf("Priyanka"));
System.out.println("lastIndexOf \"SRK\" : " + names.lastIndexOf("SRK"));

}
}

Output :Β 

Does Names LinkedList contains "Salman"? : true
indexOf "Priyanka" : 2
indexOf "John" : -1
lastIndexOf "Priyanka" : 5
lastIndexOf "SRK" : 6

Example 5: Iterating elements of Java LinkedList

Following example illustrates :

  1. Uses of Java 8Β forEach()Β and lambda expression.
  2. Uses of iterator() method.
  3. Uses of iterator() and Java 8 forEachRemaining() method.
  4. Uses of descendingIterator().
  5. Uses of listIterator() method.
  6. Uses of simple for-each loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class IterateLinkedList {
public static void main(String[] args) {

// Creating a new LinkedList
LinkedList<String> names = new LinkedList<>();

// Addition of new elements to the end of the LinkedList using add() method.
names.add("Katrina");
names.add("Varun");
names.add("Priyanka");
names.add("Arjun Kapoor");
names.add("Salman");
names.add("Priyanka");
names.add("SRK");

System.out.println("*** Iterating over a LinkedList using Java 8 forEach and lambda ***");
names.forEach(name -> {
System.out.println(name);
});


System.out.println("\n*** Iterating over a LinkedList using iterator() method ***");
Iterator<String> namesIterator = names.iterator();
while (namesIterator.hasNext()) {
String name = namesIterator.next();
System.out.println(name);
}

System.out.println("\n*** Iterating over a LinkedList using iterator() 
and Java 8 forEachRemaining() method ***");
namesIterator = names.iterator();
namesIterator.forEachRemaining(name -> {
System.out.println(name);
});

System.out.println("\n*** Iterating over a LinkedList using descendingIterator() ***");
Iterator<String> descendingnamesIterator = names.descendingIterator();
while (descendingnamesIterator.hasNext()) {
String name = descendingnamesIterator.next();
System.out.println(name);
}


System.out.println("\n*** Iterating over a LinkedList using listIterator() ***");
// ListIterator can be used to iterate over the LinkedList in both the directions :
// forward and backward.
// In this example, we are starting from the end of the list and traverse backwards
ListIterator<String> namesListIterator = names.listIterator(names.size());
while (namesListIterator.hasPrevious()) {
String name = namesListIterator.previous();
System.out.println(name);
}

System.out.println("\n*** Iterating over a LinkedList using simple for-each loop ***");
for(String name: names) {
System.out.println(name);
}

}
}

Output :

*** Iterating over a LinkedList using Java 8 forEach and lambda ***
Katrina
Varun
Priyanka
Arjun Kapoor
Salman
Priyanka
SRK

*** Iterating over a LinkedList using iterator() method ***
Katrina
Varun
Priyanka
Arjun Kapoor
Salman
Priyanka
SRK

*** Iterating over a LinkedList using iterator() and Java 8 forEachRemaining() method ***
Katrina
Varun
Priyanka
Arjun Kapoor
Salman
Priyanka
SRK

*** Iterating over a LinkedList using descendingIterator() ***
SRK
Priyanka
Salman
Arjun Kapoor
Priyanka
Varun
Katrina

*** Iterating over a LinkedList using listIterator() ***
SRK
Priyanka
Salman
Arjun Kapoor
Priyanka
Varun
Katrina

*** Iterating over a LinkedList using simple for-each loop ***
Katrina
Varun
Priyanka
Arjun Kapoor
Salman
Priyanka
SRK

Conclusion

That’s all folks! In this article, you have got the complete overview of LinkedList, its hierarchy , methods of LinkedList , how to add and remove elements in LinkedList , how to search and retrieve elements in LinkedList.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply