Java LinkedList is a doubly-linked list implementation of Java’s List and Deque interfaces. It is part of Java’s collections framework.
Learn and master Java Collections Framework at Learn Java Collections Framework
A collection is an object that represents a group of objects. A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.
Check out Linked List Data Structure:
Table of Contents
- LinkedList Class Overview
- LinkedList Class Diagram
- LinkedList Class Methods
- LinkedList Class Examples
- Example 1: Creating a LinkedList and Adding New Elements to It
- Example 2: Retrieving elements from a LinkedList
- Example 3: Removing elements from a LinkedList
- Example 4: Searching for elements in a LinkedList
- Example 5: Iterating over a LinkedList
LinkedList Class Overview
The important points about Java LinkedList are:
- Java LinkedList class can contain duplicate elements.
- Java LinkedList class maintains insertion order.
- In Java LinkedList class, manipulation is fast because no shifting needs to have occurred.
- The LinkedList class implements Queue and Deque interfaces. Therefore, It can also be used as a Queue, Deque or Stack.
- Java LinkedList is not thread-safe. You must explicitly synchronize concurrent modifications to the LinkedList in a multi-threaded environment.
LinkedList Class Diagram
The below class diagram shows hierarchical order that is LinkedList inherits the AbstractList class and implements List and Deque interfaces.
LinkedList Class Methods
The below class diagram the list of methods that the LinkedList class provides. In the next section, I have demonstrated all the methods of LinkedList class with examples.
LinkedList Class Examples
Example 1: Creating a LinkedList and Adding New Elements to It
The following example shows how to create a LinkedList and add new elements to it. Notice the uses of addFirst() and addLast() methods in the example. These methods come from the Deque interface.
package com.javaguides.collections.linkedlistexamples;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CreateLinkedListExample {
public static void main(String[] args) {
// Creating a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Adding new elements to the end of the LinkedList using add() method.
fruits.add("Banana");
fruits.add("Apple");
fruits.add("mango");
System.out.println("Initial LinkedList : " + fruits);
// Adding an element at the specified position in the LinkedList
fruits.add(2, "Watermelon");
System.out.println("After add(2, \"D\") : " + fruits);
// Adding an element at the beginning of the LinkedList
fruits.addFirst("Strawberry");
System.out.println("After addFirst(\"Strawberry\") : " + fruits);
// Adding an element at the end of the LinkedList
// (This method is equivalent to the add() method)
fruits.addLast("Orange");
System.out.println("After addLast(\"F\") : " + fruits);
// Adding all the elements from an existing collection to
// the end of the LinkedList
List<String> moreFruits = new ArrayList<>();
moreFruits.add("Grapes");
moreFruits.add("Pyrus");
fruits.addAll(moreFruits);
System.out.println("After addAll(moreFruits) : " + fruits);
}
}
Output:
Initial LinkedList : [Banana, Apple, mango]
After add(2, "D") : [Banana, Apple, Watermelon, mango]
After addFirst("Strawberry") : [Strawberry, Banana, Apple, Watermelon, mango]
After addLast("F") : [Strawberry, Banana, Apple, Watermelon, mango, Orange]
After addAll(moreFruits) : [Strawberry, Banana, Apple, Watermelon, mango, Orange, Grapes, Pyrus]
Example 2: Retrieving elements from a LinkedList
The following example shows:
- How to get the first element in the LinkedList.
- How to get the last element in the LinkedList.
- How to get the element at a given index in the LinkedList.
package com.javaguides.collections.linkedlistexamples;
import java.util.LinkedList;
public class RetrieveLinkedListElementsExample {
public static void main(String[] args) {
// Creating a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Adding new elements to the end of the LinkedList using add() method.
fruits.add("Banana");
fruits.add("Apple");
fruits.add("mango");
fruits.add("Pinaple");
// Getting the first element in the LinkedList using getFirst()
String firstElement = fruits.getFirst();
System.out.println("First Fruit in List : " + firstElement);
// Getting the last element in the LinkedList using getLast()
String lastElement = fruits.getLast();
System.out.println("Last fruit in List : " + lastElement);
// Getting the element at a given position in the LinkedList
String pinapleFruit = fruits.get(2);
System.out.println("Stock Price on 3rd Day : " + pinapleFruit);
System.out.println("Getting all the elements -> ");
// Getting all the elements
fruits.forEach( element -> {
System.out.println(element);
});
}
}
Output:
First Fruit in List : Banana
Last fruit in List : Pinaple
Stock Price on 3rd Day : mango
Getting all the elements ->
Banana
Apple
mango
Pinaple
Example 3: Removing elements from a LinkedList
The example below shows:
- How to remove the first element in the LinkedList.
- How to remove the last element in the LinkedList.
- How to remove the first occurrence of a given element in the LinkedList.
- How to remove all the elements that satisfy a given predicate from the LinkedList.
- How to clear the LinkedList completely.
package com.javaguides.collections.linkedlistexamples;
import java.util.LinkedList;
public class RemoveElementsFromLinkedListExample {
public static void main(String[] args) {
LinkedList<String> fruitList = new LinkedList<>();
fruitList.add("Apple");
fruitList.add("banana");
fruitList.add("mango");
fruitList.add("Pinaple");
System.out.println("Initial LinkedList = " + fruitList);
// Remove the first element in the LinkedList
String element = fruitList.removeFirst();
System.out.println("Removed the first element "
+ element + " => " + fruitList);
// Remove the last element in the LinkedList
element = fruitList.removeLast();
System.out.println("Removed the last element "
+ element + " => " + fruitList);
// Remove the first occurrence of the specified element from the LinkedList
boolean isRemoved = fruitList.remove("banana");
if(isRemoved) {
System.out.println("Removed banana => " + fruitList);
}
// Removes all of the elements of this collection that
// satisfy the given predicate.
fruitList.removeIf(programmingLanguage -> programmingLanguage.startsWith("C"));
System.out.println("Removed elements starting with C => " + fruitList);
//Removes all of the elements from this list.
// The list will be empty after this call returns.
fruitList.clear();
System.out.println("Cleared the LinkedList => " + fruitList);
}
}
Output:
Initial LinkedList = [Apple, banana, mango, Pinaple]
Removed the first element Apple => [banana, mango, Pinaple]
Removed the last element Pinaple => [banana, mango]
Removed banana => [mango]
Removed elements starting with C => [mango]
Cleared the LinkedList => []
Example 4: Searching for elements in a LinkedList
The example below shows:
- How to check if an element exists in a LinkedList.
- How to find the index of the first occurrence of an element in the LinkedList.
- How to find the index of the last occurrence of an element in the LinkedList.
package com.javaguides.collections.linkedlistexamples;
import java.util.LinkedList;
public class SearchLinkedListExample {
public static void main(String[] args) {
LinkedList<String> employees = new LinkedList<>();
employees.add("John");
employees.add("David");
employees.add("Lara");
employees.add("Chris");
employees.add("Steve");
employees.add("David");
// Check if the LinkedList contains an element
System.out.println("Does Employees LinkedList contain \"Lara\"? : "
+ employees.contains("Lara"));
// Find the index of the first occurrence of an element in the LinkedList
System.out.println("indexOf \"Steve\" : " + employees.indexOf("Steve"));
System.out.println("indexOf \"Mark\" : " + employees.indexOf("Mark"));
// Find the index of the last occurrence of an element in the LinkedList
System.out.println("lastIndexOf \"David\" : " + employees.lastIndexOf("David"));
System.out.println("lastIndexOf \"Bob\" : " + employees.lastIndexOf("Bob"));
}
}
Output:
Does Employees LinkedList contain "Lara"? : true
indexOf "Steve" : 4
indexOf "Mark" : -1
lastIndexOf "David" : 5
lastIndexOf "Bob" : -1
Example 5: Iterating over a LinkedList
The following example shows how to iterate over a LinkedList using
- Java 8 forEach() and lambda expression.
- iterator()
- iterator() and Java 8 forEachRemaining() method
- descendingIterator()
- listIterator()
- simple for-each loop
package com.javaguides.collections.linkedlistexamples;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class IterateOverLinkedListExample {
public static void main(String[] args) {
LinkedList < String > progLangs = new LinkedList < > ();
progLangs.add("C");
progLangs.add("C++");
progLangs.add("Core Java");
progLangs.add("Java EE");
progLangs.add("Spring Framework");
progLangs.add("Hibernate Framework");
System.out.println("=== Iterate over a LinkedList using " +
" Java 8 forEach and lambda ===");
progLangs.forEach(name - > {
System.out.println(name);
});
System.out.println("\n=== Iterate over a LinkedList using iterator() ===");
Iterator < String > iterator = progLangs.iterator();
while (iterator.hasNext()) {
String speciesName = iterator.next();
System.out.println(speciesName);
}
System.out.println("\n=== Iterate over a LinkedList using iterator() " +
" and Java 8 forEachRemaining() method ===");
iterator = progLangs.iterator();
iterator.forEachRemaining(speciesName - > {
System.out.println(speciesName);
});
System.out.println("\n=== Iterate over a LinkedList " +
" using descendingIterator() ===");
Iterator < String > descendingIterator = progLangs.descendingIterator();
while (descendingIterator.hasNext()) {
String speciesName = descendingIterator.next();
System.out.println(speciesName);
}
System.out.println("\n=== Iterate over a LinkedList using listIterator() ===");
// ListIterator can be used to iterate over the LinkedList in both forward and
// backward directions
// In this example, we start from the end of the list and traverse backwards
ListIterator < String > listIterator = progLangs.listIterator(progLangs.size());
while (listIterator.hasPrevious()) {
String speciesName = listIterator.previous();
System.out.println(speciesName);
}
System.out.println("\n=== Iterate over a LinkedList " +
" using simple for-each loop ===");
for (String name: progLangs) {
System.out.println(name);
}
}
}
Output:
=== Iterate over a LinkedList using Java 8 forEach and lambda ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework
=== Iterate over a LinkedList using iterator() ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework
=== Iterate over a LinkedList using iterator() and Java 8 forEachRemaining() method ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework
=== Iterate over a LinkedList using descendingIterator() ===
Hibernate Framework
Spring Framework
Java EE
Core Java
C++
C
=== Iterate over a LinkedList using listIterator() ===
Hibernate Framework
Spring Framework
Java EE
Core Java
C++
C
=== Iterate over a LinkedList using simple for-each loop ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework
Reference
Related Collections Examples
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course