This example shows how Deque in Java works.
public interface Deque<E> extends Queue<E>
A linear collection that supports element insertion and removal at both ends. This interface defines methods to access the elements at both ends of the Deque. Methods are provided to insert, remove, and examine the element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; public class DequeExample { public static void main(String[] args) { Deque deque = new LinkedList<>(); // We can add elements to the queue in various ways deque.add("Element 1 (Tail)"); // add to tail deque.addFirst("Element 2 (Head)"); deque.addLast("Element 3 (Tail)"); deque.push("Element 4 (Head)"); //add to head deque.offer("Element 5 (Tail)"); deque.offerFirst("Element 6 (Head)"); deque.offerLast("Element 7 (Tail)"); System.out.println(deque + "\n"); // Iterate through the queue elements. System.out.println("Standard Iterator"); Iterator iterator = deque.iterator(); while (iterator.hasNext()) { System.out.println("\t" + iterator.next()); } // Reverse order iterator Iterator reverse = deque.descendingIterator(); System.out.println("Reverse Iterator"); while (reverse.hasNext()) { System.out.println("\t" + reverse.next()); } // Peek returns the head, without deleting it from the deque System.out.println("Peek " + deque.peek()); System.out.println("After peek: " + deque); // Pop returns the head, and removes it from the deque System.out.println("Pop " + deque.pop()); System.out.println("After pop: " + deque); // We can check if a specific element exists in the deque System.out.println("Contains element 3: " + deque.contains("Element 3 (Tail)")); // We can remove the first/last element. deque.removeFirst(); deque.removeLast(); System.out.println("Deque after removing first and last: " + deque); } } |
Output:
Standard Iterator
Element 6 (Head)
Element 4 (Head)
Element 2 (Head)
Element 1 (Tail)
Element 3 (Tail)
Element 5 (Tail)
Element 7 (Tail)
Reverse Iterator
Element 7 (Tail)
Element 5 (Tail)
Element 3 (Tail)
Element 1 (Tail)
Element 2 (Head)
Element 4 (Head)
Element 6 (Head)
Peek Element 6 (Head)
After peek: [Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail), Element 7 (Tail)]
Pop Element 6 (Head)
After pop: [Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail), Element 7 (Tail)]
Contains element 3: true