Java LinkedList

LinkedList in java is a resizable array like ArrayList. There is no size limit in LinkedList. When you add new elements or items in the LinkedList, the size or capacity of LinkedList will grow. You can do many things like add new elements, remove elements, change elements, sort the elements etc. like ArrayList. Both ArrayList and LinkedList implements List interface. Thus, possibly all the methods you can use in the ArrayList can also be used in LinkedList.

Additionally, LinkedList provides additional methods to manipulate your data.

# Methods for LinkedList:


MethodsReturn typesDescription
add(E element)booleanAppends the specified element to the end of this list.
add(int index, E element)voidInserts the specified element at the specified position in this list.
addAll(Collection c)booleanAppends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.
addAll(int index, Collection c)booleanAppends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.
get(int index)E (element type)Returns the element at the specified position in this list.
isEmpty()booleanReturns true if this list contains no elements.
iterator()Iterator(E)Returns an iterator over the elements in this list in proper sequence.
remove(int index)ERemoves the element at the specified position in this list.
removeAll(Collection c)booleanRemoves from this list all of its elements that are contained in the specified collection.
removeIf(Predicate filter)booleanRemoves all of the elements of this collection that satisfy the given predicate.
set(int index, E element)EReplaces the element at the specified position in this list with the specified element.
size()intReturns the number of elements in this list.
trimToSize()voidTrims the capacity of this ArrayList instance to be the list's current size.
toArray()ObjectReturns an array containing all of the elements in this list in proper sequence (from first to last element).
contains()booleanReturns true if this list contains the specified element
clone()ObjectReturns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)
equals()booleanChecks two lists are equal or not (returns true ir false)
indexOf()intReturns the index of the first occurrence of the specified element in this list.
indexOf()intReturns the index of the last occurrence of the specified element in this list.
sort()voidSorts the list alphabetically or numerically in a specified order (Eescending or Descending)
stream()StreamReturns a sequential Stream with this collection as its source.
addFirst()voidInsert new element at the beginning of the LinkedList.
addLast()voidInsert new element at the end of the list.
getFirst()Get the item of first position of the list.
getLast()Retrieve the last element of the list.
removeFirst()Remove the first element from the list.
removeLast()Remove the last element from the list.
clear()voidRemove all the elements from the list.
clone()ObjectReturns a shallow copy of the list.
poll()ERetrieves and then remove the first element of the list.
peek()ERetrieves but doesn't remove the first element.



# Creating LinkedList

Syntax:

Non generic:


LinkedList list = new LinkedList();

Generic approach: (with wrapper types)

LinkedList list = new LinkedList(); 

//T stands for type but wrapper. Primitive is not supported.

//such as 
LinkedList list = new LinkedList(); 

Below is a simple example, where we created a LinkedList object and add String data using add() method.


public class Main{
  public static void main (String[] args){
    //creating LinkedList
    LinkedList fruits = new LinkedList(); 
    //add new elements
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry")
    fruits.add("Guava");
    fruits.add("Blackberry");
    
    //print the elements
    System.out.println(fruits);
  }
}

/**
 * Output: 
 * [Apple, Banana, Cherry, Guava, Blackberr]
 */

# Removing elements from the LinkedList


import java.util.LinkedList;
 
 public class Main{
  public static void main (String[] args){
    //creating LinkedList
    LinkedList fruits = new LinkedList(); 
    //add new elements
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Blackberry");
    
    //print the elements
    System.out.println(fruits);
    
    //remove the first element
    fruits.remove("Apple");
    //Now print the above fruits list
    System.out.println(fruits);
  }
}

/**
 * Output: 
 * [Apple, Banana, Cherry, Guava, Blackberr]
 * After removing
 * [Banana, Cherry, Guava, Blackberry]
 */

Note: remove(0) also works the same. One is based on element and other one is position.

# Change an LinkedList element using set() method


import java.util.ArrayList;

public class Main{
  public static void main (String[] args){
    LinkedList fruits = new LinkedList();

    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
 
    //iterating LinkedList elements
    System.out.println("Before Changing");
    for(String f: fruits){
      System.out.println(f);
    }
    
    //change the fruits and then iterate
    System.out.println("After changing");
    fruits.set(0, "Blueberry");
    //iterate now 
    for(String f: fruits){
      System.out.println(f);
    }
  }
}

If you run the above program, you will get the following output in the console. You can see, the first fruit element has been updated.


Before Changing
Apple
Banana
Cherry
Guava
Plum
After changing
Blueberry
Banana
Cherry
Guava
Plum

Note: The add(int index, element) and set(int index, element) can be used interchangeably

# Iterate LinkedList elements

# For iterating LinkedList elements we can use java for loop.


import java.util.LinkedList;

public class Main{
  public static void main (String[] args){
    LinkedList fruits = new LinkedList();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
    
    //iterate
    for(int i = 0; i <=fruits.size(); i++){
      System.out.println(fruits.get(i));
    }
  }
}

If you run the above example you get the following output:

Apple Banana Cherry Guava Plum

# Iterating LinkedList elements using for each loop.


import java.util.LinkedList;

public class Main{
  public static void main (String[] args){
    LinkedList fruits = new LinkedList();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
    
    //iterate and print 
    for(String f: fruits){
      System.out.println(f);
    }
  }
}
/**
 * Apple
 * Banana
 * Cherry
 * Guava
 * Plum
 */

# Iterating LinkedList using Iterator


import java.util.LinkedList;
import java.util.Iterator;
//import all the classes 
//import java.util.*;
 
 public class Main{
   public static void main (String[] args) {
     //Creating ArrayList
     LinkedList fruits = new LinkedList();
     //add elements to this ArrayList
     fruits.add("Apple");
     fruits.add("Banana");
     fruits.add("Cherry");
     fruits.add("Guava");
     fruits.add("Plum");
     
     //iterate using Iterator
     Iterator list = fruits.iterator(); //getting Iterator
     while(list.hasNext()){ //check if any elements exists or not
       System.out.println(list.next()); //printing the elements 
     }
   }
 }
 
/**
 * Apple
 * Banana
 * Cherry
 * Guava
 * Plum
 */

# Using addFirst(), addLast(), removeFast(), removeLast() methods in LinkedList


import java.util.LinkedList;
 
 public class Main{
  public static void main (String[] args){
    //creating LinkedList
    LinkedList fruits = new LinkedList(); 
    //add new elements
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Blackberry");
    
    //print the elements
    System.out.println(fruits);
    
    //addFirst() 
    fruits.addFirst("Orange");
    
    //Now print the above fruits list
    System.out.println(fruits);
    
   //addLast() 
   fruits.addLast("Plum")
   //now print fruits
   System.out.println(fruits);
   
   //removeFast()
   fruits.removeFirst();
   //print the list
   System.out.println(fruits);
   
   //removeLast()
   fruits.removeLast();
   //print the list now
   System.out.println(fruits);
  }
}

After running the above program, you will get the following output. Now think, what's going on here?


[Apple, Banana, Cherry, Guava, Blackberry]
[Orange, Apple, Banana, Cherry, Guava, Blackberry]
[Orange, Apple, Banana, Cherry, Guava, Blackberry, Plum]
[Apple, Banana, Cherry, Guava, Blackberry, Plum]
[Apple, Banana, Cherry, Guava, Blackberry]