What is Queue in Java: Explanation and Example
Queue is a collection that stores elements in a specific order, usually following the First-In-First-Out (FIFO) principle. It allows adding elements at the end and removing them from the front, similar to a real-life line or queue.How It Works
A Queue in Java works like a line of people waiting for a service. The first person to get in line is the first one to be served and leave the line. This is called First-In-First-Out (FIFO).
When you add something to a queue, it goes to the back of the line. When you remove something, it comes from the front. This way, the order of elements is kept.
Queues are useful when you want to process things in the order they arrive, like tasks waiting to be done or messages waiting to be read.
Example
This example shows how to create a queue, add elements, and remove them in order.
import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); // Add elements to the queue queue.add("Apple"); queue.add("Banana"); queue.add("Cherry"); System.out.println("Queue: " + queue); // Remove elements from the queue String first = queue.poll(); System.out.println("Removed: " + first); System.out.println("Queue after removal: " + queue); } }
When to Use
Use a Queue when you need to process items in the order they arrive. For example:
- Handling tasks in a printer queue where documents print one by one.
- Managing requests in a web server to serve clients fairly.
- Processing messages in a chat app so they appear in the right order.
Queues help keep things organized and fair by ensuring the first item added is the first one handled.
Key Points
- Queue follows FIFO order: first added, first removed.
- Java provides
Queueinterface and classes likeLinkedListto use queues. - Common methods:
add()to insert,poll()to remove. - Useful for managing tasks, requests, or messages in order.