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.example.util;

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

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

        Deque deque2 = new LinkedList();
        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());
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply