Queue and Deque in Java

Category : Java | Sub Category : Java.util Package | By Prasad Bonam Last updated: 2023-07-12 11:01:25 Viewed : 327


Queue and Deque in Java:

Here are examples of using Queue and Deque in Java:

Queue Example:

java
import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { // Create a Queue of strings Queue<String> queue = new LinkedList<>(); // Add elements to the Queue queue.offer("Alice"); queue.offer("Bob"); queue.offer("Charlie"); // Access elements System.out.println("Element at the front of the queue: " + queue.peek()); // Remove elements String removedElement = queue.poll(); System.out.println("Removed element: " + removedElement); System.out.println("Size after removing an element: " + queue.size()); // Iterate over the Queue System.out.println("Elements in the Queue:"); for (String element : queue) { System.out.println(element); } } }

Deque Example:

java
import java.util.ArrayDeque; import java.util.Deque; public class DequeExample { public static void main(String[] args) { // Create a Deque of integers Deque<Integer> deque = new ArrayDeque<>(); // Add elements to the front and back of the Deque deque.offerFirst(10); deque.offerLast(20); deque.offerLast(30); // Access elements System.out.println("First element: " + deque.peekFirst()); System.out.println("Last element: " + deque.peekLast()); // Remove elements int removedElement = deque.pollFirst(); System.out.println("Removed element: " + removedElement); System.out.println("Size after removing an element: " + deque.size()); // Iterate over the Deque System.out.println("Elements in the Deque:"); for (int element : deque) { System.out.println(element); } } }

In these examples, we create instances of Queue (using LinkedList) and Deque (using ArrayDeque), and perform operations such as adding elements, accessing elements, removing elements, and iterating over the collections.

For Queue, we use the offer() method to add elements, peek() method to access the element at the front of the queue, and poll() method to remove elements. The Queue follows the FIFO (First-In-First-Out) principle.

For Deque, we use the offerFirst() and offerLast() methods to add elements at the front and back, peekFirst() and peekLast() methods to access the first and last elements, and pollFirst() method to remove the first element. Deque can be used as both a queue and a stack.

Both Queue and Deque allow you to iterate over the elements using a for-each loop or any other applicable iteration method.

These examples demonstrate basic usage and functionality of Queue and Deque in Java. You can further explore additional methods and capabilities of these interfaces based on your specific requirements.


Search
Related Articles

Leave a Comment: