java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.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<String>();
        deque1.offer("a");
        deque1.offer("b");
        deque1.offer("c");
        deque1.offer("d");
        deque1.offer("e");
        deque1.offer("d");

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

        //
        // Removes the first occurrence of the specified element
        // from this deque
        //
        deque1.removeFirstOccurrence("d");

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

        //
        // Removes the first occurrence of the specified element
        // from this deque
        //
        deque2.removeLastOccurrence("d");
        Iterator last = deque2.iterator();
        System.out.println("nAfter removeLastOccurrence(Object o): ");
        System.out.println("========================================");
        while (last.hasNext()) {
            System.out.println(last.next());
        }
    }
}