How do you use Queue with a simple code example?

In Java, a Queue is a data structure that holds elements prior to processing. It follows the First-In-First-Out (FIFO) principle, meaning that the first element added to the queue will be the first one removed. The Queue interface is a part of the Java Collections Framework and can be implemented using various classes, including LinkedList or PriorityQueue.

Here is a simple code example demonstrating how to use a Queue in Java:

import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { // Create a Queue Queue queue = new LinkedList<>(); // Add elements to the Queue queue.offer("Element 1"); queue.offer("Element 2"); queue.offer("Element 3"); // Display the Queue System.out.println("Queue: " + queue); // Remove an element from the Queue String removedElement = queue.poll(); System.out.println("Removed: " + removedElement); // Display the Queue after removal System.out.println("Queue after removal: " + queue); } }

Queue Java Data Structure Collections Framework