How do I remove elements from Deque?

This example shows you how to removes 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.example.util;

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

public class RemoveDequeDemo {
    public static void main(String[] args) {
        Deque 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);
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply