Deque in Java

Deque in Java

Deque (pronounced "deck") stands for Double Ended Queue. It's a part of the Java Collections framework, introduced in Java 6, and allows us to add or remove elements from both ends.

1. Importing Necessary Packages:

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

2. Deque Basics:

Deque is an interface, and you need a concrete class to create an instance. The most commonly used class is LinkedList.

Deque<String> deque = new LinkedList<>(); 

3. Adding Elements:

  • addToFront: Use addFirst() to add an element to the front.

    deque.addFirst("Element1 (Head)"); 
  • addToEnd: Use addLast() to add an element to the end.

    deque.addLast("Element3 (Tail)"); 
  • You can also use offerFirst() and offerLast() which return true or false based on the success of the insertion.

4. Removing Elements:

  • removeFromFront: Use removeFirst() to remove an element from the front. This method throws an exception if the deque is empty.

    deque.removeFirst(); 
  • removeFromEnd: Use removeLast() to remove an element from the end. This method throws an exception if the deque is empty.

    deque.removeLast(); 
  • There are also pollFirst() and pollLast() which return null if the deque is empty.

5. Retrieving Elements:

  • getFront: Use getFirst() to retrieve the front element without removing it.

    String firstElement = deque.getFirst(); 
  • getEnd: Use getLast() to retrieve the end element without removing it.

    String lastElement = deque.getLast(); 

6. Other Useful Methods:

  • isEmpty: Check if the deque is empty.

    boolean isEmpty = deque.isEmpty(); 
  • size: Return the number of elements in the deque.

    int size = deque.size(); 
  • clear: Remove all elements.

    deque.clear(); 
  • contains: Check if an element is present.

    boolean contains = deque.contains("Element1"); 

7. Iterating Over a Deque:

You can use the enhanced for loop:

for (String element : deque) { System.out.println(element); } 

8. Example:

Here's a simple example demonstrating a Deque's operations:

public class DequeExample { public static void main(String[] args) { Deque<String> deque = new LinkedList<>(); // Add to the deque deque.addFirst("Element1 (Head)"); deque.addLast("Element2"); deque.addLast("Element3 (Tail)"); // Display the elements for (String element : deque) { System.out.println(element); } // Remove elements deque.removeFirst(); deque.removeLast(); System.out.println("Deque after removing elements:"); for (String element : deque) { System.out.println(element); } } } 

Conclusion:

Deque is a versatile data structure that can serve as both a queue and a stack. Its double-ended operations make it suitable for various scenarios where elements need to be added or removed from both ends.


More Tags

sql-null combinations tkinter-entry swift4 pdf-generation primefaces qfiledialog wsgi visual-studio-2013 optional-parameters

More Programming Guides

Other Guides

More Programming Examples