How do I remove elements from Deque?

This example shows you how to remove some elements from the Deque object. We can use the following methods for removing elements from Deque: remove(), remove(Object o), removeFirst(), removeLast().

package org.kodejava.util;

import java.util.Deque;
import java.util.LinkedList;

public class RemoveDequeDemo {
    public static void main(String[] args) {
        Deque<String> deque = new LinkedList<>();
        deque.add("A");
        deque.add("B");
        deque.add("C");
        deque.add("D");
        deque.add("E");
        deque.add("F");

        // Removes and retrieves the head of this Deque
        deque.remove();      // Removes "A"

        // Removes the first occurrence of element from this Deque
        deque.remove("F");   // Removes "F"

        // Retrieves and removes the first element of this deque
        deque.removeFirst(); // Removes "B"

        // Retrieves and removes the last element of this deque
        deque.removeLast();  // Removes "E"

        for (String item : deque) {
            System.out.println("Item = " + item);
        }
    }
}

How do I add elements into a Deque?

To add elements into a Deque object we can use the add(), addFirst() and addLast() method call.

package org.kodejava.util;

import java.util.Deque;
import java.util.LinkedList;

public class DequeAddElement {
    public static void main(String[] args) {
        // Create an instance of Deque using LinkedList class.
        Deque<String> deque = new LinkedList<>();

        // Insert a word into the Deque
        deque.add("jumps");

        // Insert words at the beginning of the current Deque
        // elements
        deque.addFirst("fox");
        deque.addFirst("brown");
        deque.addFirst("quick");
        deque.addFirst("The");

        // Insert words at the end of the current Deque elements
        deque.addLast("over");
        deque.addLast("the");
        deque.addLast("lazy");
        deque.addLast("dog");

        for (String word : deque) {
            System.out.println("Word = " + word);
        }
    }
}

Here is the output:

Word = The
Word = quick
Word = brown
Word = fox
Word = jumps
Word = over
Word = the
Word = lazy
Word = dog

How do I remove the first or the last found element from Deque?

This example demonstrates the use of Deque.removeFirstOccurrence() method call to remove the first occurrences of an element in the Deque object and Deque.removeLastOccurrence() method call to remove the last occurrences of an element in the Deque object.

package org.kodejava.util;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

public class DequeRemoveDemo {
    public static void main(String[] args) {
        Deque<String> deque1 = new LinkedList<>();
        deque1.offer("a");
        deque1.offer("b");
        deque1.offer("c");
        deque1.offer("d");
        deque1.offer("e");
        deque1.offer("d");

        Deque<String> deque2 = new LinkedList<>(deque1);

        // Removes the first occurrence of letter "d" from deque1
        deque1.removeFirstOccurrence("d");

        Iterator<String> first = deque1.iterator();
        System.out.println("After removeFirstOccurrence(Object o): ");
        System.out.println("=======================================");
        while (first.hasNext()) {
            System.out.println(first.next());
        }

        // Removes the last occurrence of letter "d" from deque2
        deque2.removeLastOccurrence("d");
        Iterator<String> last = deque2.iterator();
        System.out.println("After removeLastOccurrence(Object o): ");
        System.out.println("========================================");
        while (last.hasNext()) {
            System.out.println(last.next());
        }
    }
}

The output of the code snippet above is:

After removeFirstOccurrence(Object o): 
=======================================
a
b
c
e
d
After removeLastOccurrence(Object o): 
========================================
a
b
c
d
e

How do I sort LinkedList elements?

To sort the elements of LinkedList we can use the Collections.sort(List<T> list) static methods. The default order of the sorting is a descending order.

package org.kodejava.util;

import java.util.LinkedList;
import java.util.Collections;

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("E");
        grades.add("C");
        grades.add("A");
        grades.add("F");
        grades.add("B");
        grades.add("D");

        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        // Sort the elements of linked list based on its data
        // natural order.
        Collections.sort(grades);

        System.out.println("After sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are:

Before sorting:
===============
Grade = E
Grade = C
Grade = A
Grade = F
Grade = B
Grade = D
After sorting:
===============
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F

How do I get the first and the last element of a LinkedList?

The get the first element we can use the LinkedList.getFirst() method and to get the last element we can use the LinkedList.getLast() method.

package org.kodejava.util;

import java.util.LinkedList;

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

        // Get the first and the last element of the linked list
        String first = names.getFirst();
        String last = names.getLast();

        System.out.println("First member = " + first);
        System.out.println("Last member  = " + last);
    }
}

The program will print the following result:

First member = Alice
Last member  = Mallory

How do I reverse the order of LinkedList elements?

To reverse the order of LinkedList elements we can use the reverse(List<?> list) static method of java.util.Collections class. Here is the example:

package org.kodejava.util;

import java.util.LinkedList;
import java.util.Collections;

public class LinkedListReverseOrder {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");
        grades.add("F");

        System.out.println("Output in original order:");
        System.out.println("=========================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        // Reverse the element order in the linked list object.
        Collections.reverse(grades);

        System.out.println("Output in reverse order:");
        System.out.println("=========================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

Here is the output of the program:

Output in original order:
=========================
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F
Output in reverse order:
=========================
Grade = F
Grade = E
Grade = D
Grade = C
Grade = B
Grade = A

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.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

How do I insert an item into LinkedList?

To insert an item at any position into a linked list object we can use the add(int index, Object o) method. This method takes the index to where the new object to be inserted and the object to be inserted itself.

package org.kodejava.util;

import java.util.LinkedList;

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

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

        // Add a new item to the list at index number 2. Because
        // a list are 0 based index Carol will be inserted after
        // Bob.
        names.add(2, "Carol");

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

The result of our program are:

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

How do I add item at the beginning or the end of LinkedList?

To add an item before the first item in the linked list we use the LinkedList.addFisrt() method and to add an items after the last item in the linked list we use the LinkedList.addLast() method.

package org.kodejava.util;

import java.util.LinkedList;

public class LinkedListAddItems {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        System.out.println("Original values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        grades.addFirst("A");
        grades.addLast("F");

        System.out.println("New values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are the following:

Original values are:
====================
Grade = B
Grade = C
Grade = D
Grade = E
New values are:
====================
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F

How do I remove the first and last item from LinkedList?

To remove the first or the last elements from the linked list we can use the removeFirst() and removeLast() methods provided by the LinkedList class.

package org.kodejava.util;

import java.util.LinkedList;

public class LinkedListRemoveItems {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");
        grades.add("F");

        System.out.println("Original values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade: " + grade);
        }

        grades.removeFirst();
        grades.removeLast();

        System.out.println("New values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade: " + grade);
        }
    }
}

This program print out the following result:

Original values are:
====================
Grade: A
Grade: B
Grade: C
Grade: D
Grade: E
Grade: F
New values are:
====================
Grade: B
Grade: C
Grade: D
Grade: E