Java如何从Deque中删除第一个或最后一个找到的元素?

本示例演示如何使用Deque.removeFirstOccurrence()方法调用删除Deque对象中元素的第一次出现,以及使用Deque.removeLastOccurrence()方法调用删除Deque对象中元素的最后出现。

package org.nhooo.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<>();
        deque1.offer("a");
        deque1.offer("b");
        deque1.offer("c");
        deque1.offer("d");
        deque1.offer("e");
        deque1.offer("d");

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

        // 从双端队列1中删除字母“ d”的第一个匹配项"d" from deque1
        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());
        }

        // 从双端队列2中删除最后一次出现的字母“ d”"d" from deque2
        deque2.removeLastOccurrence("d");
        Iterator last = deque2.iterator();
        System.out.println("After removeLastOccurrence(Object o): ");
        System.out.println("========================================");
        while (last.hasNext()) {
            System.out.println(last.next());
        }
    }
}