0% found this document useful (0 votes)
3 views

Gmail - Queue

The Queue interface in Java, part of the java.util package, represents a collection of elements in FIFO order and provides methods for adding, removing, and examining elements. Key implementations include LinkedList, PriorityQueue, and ArrayDeque, each serving different use cases such as task scheduling and priority handling. Additionally, the document covers various queue operations, examples, and advanced features like BlockingQueue for concurrency management.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Gmail - Queue

The Queue interface in Java, part of the java.util package, represents a collection of elements in FIFO order and provides methods for adding, removing, and examining elements. Key implementations include LinkedList, PriorityQueue, and ArrayDeque, each serving different use cases such as task scheduling and priority handling. Additionally, the document covers various queue operations, examples, and advanced features like BlockingQueue for concurrency management.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Queue

1 message

Nagasai Maddula <[email protected]> Sun, 19 Jan, 2025 at 15:20


To: Nagasai Maddula <[email protected]>

Queue Interface in Java

The Queue interface is part of the java.util package and is designed to represent a collection that holds elements in a FIFO (First-In-First-
Out) order. It provides various methods to insert, remove, and examine elements in the queue.

How it Works:

FIFO Order: Elements are added to the end of the queue (enqueue), and elements are removed from the front of the queue
(dequeue).
Primary Methods: add(), remove(), peek(), poll(), etc.

Queues are used in scenarios like task scheduling, message processing, and handling asynchronous requests.

Queue Interface Methods:

1. add(E e)

Description: Inserts the specified element into the queue if possible.


Return Type: boolean (returns true if the element was added successfully).
Throws: IllegalStateException if the queue is full.

2. offer(E e)

Description: Adds the element to the queue if space is available. Returns false if the queue is full.
Return Type: boolean
Throws: IllegalStateException (only if the queue is full and no space is available).

3. remove()

Description: Removes and returns the head (first element) of the queue. Throws an exception if the queue is empty.
Return Type: E (element type)
Throws: NoSuchElementException if the queue is empty.

4. poll()

Description: Removes and returns the head of the queue, or returns null if the queue is empty.
Return Type: E
Throws: None (returns null if empty).

5. peek()

Description: Retrieves but does not remove the head of the queue. Returns null if the queue is empty.
Return Type: E
Throws: None

6. element()

Description: Retrieves but does not remove the head of the queue. Throws an exception if the queue is empty.
Return Type: E
Throws: NoSuchElementException if the queue is empty.

7. size()

Description: Returns the number of elements in the queue.


Return Type: int

8. clear()

Description: Removes all elements from the queue.


Return Type: void

Queue Classes

1. LinkedList
LinkedList implements the Queue interface and is one of the most commonly used queue classes. It provides the behavior
of a queue along with the ability to use it as a list.

2. PriorityQueue

A priority queue is a queue where elements are ordered based on their natural ordering or by a comparator provided at the
time of creation. It does not guarantee FIFO order, but instead, elements with higher priority are dequeued first.

3. ArrayDeque

ArrayDeque is a resizable array implementation of the Deque interface, which is a more generalized form of a queue that
allows elements to be added or removed from both ends.

4. PriorityBlockingQueue

A specialized blocking queue that supports the priority ordering of elements.

Queue Operations with Examples

1. LinkedList Queue Example (FIFO behavior):

import java.util.*;

public class QueueExample {


public static void main(String[] args) {
// Create a LinkedList Queue
Queue<String> queue = new LinkedList<>();

// Enqueue: Add elements to the queue


queue.add("Alice");
queue.add("Bob");
queue.add("Charlie");

// Display the queue


System.out.println("Queue: " + queue); // Output: [Alice, Bob, Charlie]

// Peek: View the front element without removing it


System.out.println("Front element: " + queue.peek()); // Output: Alice

// Dequeue: Remove elements from the front of the queue


System.out.println("Removed: " + queue.remove()); // Output: Alice
System.out.println("Queue after removal: " + queue); // Output: [Bob, Charlie]

// Poll: Retrieve and remove the front element (returns null if empty)
System.out.println("Polled: " + queue.poll()); // Output: Bob
System.out.println("Queue after polling: " + queue); // Output: [Charlie]

// Size of the queue


System.out.println("Size of queue: " + queue.size()); // Output: 1
}
}

2. PriorityQueue Example (Ordered by Natural Order):

import java.util.*;

public class PriorityQueueExample {


public static void main(String[] args) {
// Create a PriorityQueue (ordered by natural order)
Queue<Integer> priorityQueue = new PriorityQueue<>();

// Enqueue elements
priorityQueue.add(50);
priorityQueue.add(20);
priorityQueue.add(40);
priorityQueue.add(10);

// Display the queue


System.out.println("Priority Queue: " + priorityQueue); // Output: [10, 20, 40, 50]

// Peek: View the front element (smallest)


System.out.println("Front element: " + priorityQueue.peek()); // Output: 10

// Dequeue: Remove elements from the front (smallest)


System.out.println("Removed: " + priorityQueue.remove()); // Output: 10
System.out.println("Queue after removal: " + priorityQueue); // Output: [20, 40, 50]

// Poll: Remove the front element (returns null if empty)


System.out.println("Polled: " + priorityQueue.poll()); // Output: 20
System.out.println("Queue after polling: " + priorityQueue); // Output: [40, 50]
// Size of the queue
System.out.println("Size of queue: " + priorityQueue.size()); // Output: 2
}
}

3. ArrayDeque Example (Deque with queue behavior):

import java.util.*;

public class ArrayDequeExample {


public static void main(String[] args) {
// Create an ArrayDeque (double-ended queue)
Queue<String> queue = new ArrayDeque<>();

// Enqueue elements
queue.add("X");
queue.add("Y");
queue.add("Z");

// Display the queue


System.out.println("Queue: " + queue); // Output: [X, Y, Z]

// Peek: View the front element


System.out.println("Front element: " + queue.peek()); // Output: X

// Dequeue: Remove elements


System.out.println("Removed: " + queue.remove()); // Output: X
System.out.println("Queue after removal: " + queue); // Output: [Y, Z]

// Poll: Retrieve and remove the front element


System.out.println("Polled: " + queue.poll()); // Output: Y
System.out.println("Queue after polling: " + queue); // Output: [Z]

// Size of the queue


System.out.println("Size of queue: " + queue.size()); // Output: 1
}
}

Sorting in Queue

For most Queue implementations like LinkedList or ArrayDeque, you cannot directly sort the queue elements. However, you can convert
the queue to a list, sort it, and then reinsert the elements back into the queue.

Sorting a Queue:

import java.util.*;

public class QueueSortingExample {


public static void main(String[] args) {
// Create a LinkedList Queue
Queue<Integer> queue = new LinkedList<>();
queue.add(30);
queue.add(10);
queue.add(50);
queue.add(20);

// Convert Queue to a List


List<Integer> list = new ArrayList<>(queue);

// Sort the List


Collections.sort(list);

// Clear the Queue


queue.clear();

// Re-insert sorted elements back into the Queue


queue.addAll(list);

// Display the sorted Queue


System.out.println("Sorted Queue: " + queue); // Output: [10, 20, 30, 50]
}
}

Summary of Queue Operations

When to Use Queue?

Queue is used when you need to process elements in the order they arrive (FIFO).
PriorityQueue is ideal for scenarios where elements have a priority, and you need to serve higher-priority elements first.
ArrayDeque is best when you need a resizable array implementation of a queue, especially if you need to add and remove elements
quickly from both ends.

Additional Queue Implementations and Methods

Here are more details about queue implementations and how they can be used in real-time applications, such as PriorityQueue,
ArrayDeque, and BlockingQueue, among others.

1. PriorityQueue (Advanced Version)

PriorityQueue is an unbounded queue that orders elements according to their natural ordering or by a Comparator provided at the
time of creation.
The elements are dequeued in the order of their priority, which is determined by their natural order (ascending order for comparable
types) or a custom comparator.

Methods of PriorityQueue:

add(E e): Adds an element to the queue.


offer(E e): Similar to add(), but it returns false if the element can't be added due to space constraints.
peek(): Retrieves, but does not remove, the head of the queue, or returns null if the queue is empty.
poll(): Retrieves and removes the head of the queue. Returns null if the queue is empty.
remove(Object o): Removes a specific element from the queue.
clear(): Removes all elements from the queue.

Example:

import java.util.*;

public class PriorityQueueExample {


public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();

pq.add(30);
pq.add(20);
pq.add(50);
pq.add(10);

// Display the elements in the queue (not in the order they were added)
System.out.println("PriorityQueue: " + pq); // Output: [10, 20, 50, 30]

// Removing elements in order of priority (ascending)


while (!pq.isEmpty()) {
System.out.println("Polled: " + pq.poll());
}
}
}

Output:

Polled: 10
Polled: 20
Polled: 30
Polled: 50

2. ArrayDeque (A Dynamic Queue)

ArrayDeque is an implementation of the Deque interface, which allows elements to be added or removed from both ends.
It is a resizable array implementation of a queue and provides better performance than LinkedList for queue operations, as it does
not require node allocations.

Methods of ArrayDeque:

addFirst(E e): Adds an element at the front of the deque.


addLast(E e): Adds an element at the end of the deque.
offerFirst(E e): Inserts an element at the front, returning false if the deque is full.
offerLast(E e): Inserts an element at the end, returning false if the deque is full.
removeFirst(): Removes and returns the first element of the deque.
removeLast(): Removes and returns the last element of the deque.
pollFirst(): Retrieves and removes the first element, or returns null if empty.
pollLast(): Retrieves and removes the last element, or returns null if empty.

Example:

import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();

deque.add("First");
deque.add("Second");
deque.add("Third");

// Add elements at both ends


deque.addFirst("Zero");
deque.addLast("Fourth");

// Display the deque


System.out.println("Deque: " + deque); // Output: [Zero, First, Second, Third, Fourth]

// Poll elements from both ends


System.out.println("Poll First: " + deque.pollFirst()); // Output: Zero
System.out.println("Poll Last: " + deque.pollLast()); // Output: Fourth

// Display the deque after polling


System.out.println("Deque after polling: " + deque); // Output: [First, Second, Third]
}
}

3. BlockingQueue (Thread-Safe Queue for Concurrency)

BlockingQueue is an interface that extends Queue and is designed for use in multi-threaded environments. It supports operations that
block (wait) until certain conditions are met, making it useful for producer-consumer problems.

Types of BlockingQueue:
ArrayBlockingQueue: A bounded blocking queue backed by an array.
LinkedBlockingQueue: An optionally bounded queue backed by a linked node structure.
PriorityBlockingQueue: A priority-based blocking queue.
SynchronousQueue: A special type of queue where each insert operation must wait for a corresponding remove operation by
another thread.

Common Methods:

put(E e): Inserts the specified element into the queue, waiting if necessary for space to become available.
take(): Retrieves and removes the head of the queue, waiting if necessary for an element to become available.
offer(E e, long timeout, TimeUnit unit): Inserts the element into the queue if space is available within the specified time.
poll(long timeout, TimeUnit unit): Retrieves and removes the head of the queue, waiting if necessary for the specified time.

Example (Using ArrayBlockingQueue):

import java.util.concurrent.*;

public class BlockingQueueExample {


public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

// Producer Thread
Thread producer = new Thread(() -> {
try {
queue.put("Item1");
queue.put("Item2");
queue.put("Item3");
System.out.println("Items added to the queue.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});

// Consumer Thread
Thread consumer = new Thread(() -> {
try {
System.out.println("Consumed: " + queue.take());
System.out.println("Consumed: " + queue.take());
System.out.println("Consumed: " + queue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});

producer.start();
consumer.start();

producer.join();
consumer.join();
}
}

Output:

Items added to the queue.


Consumed: Item1
Consumed: Item2
Consumed: Item3

4. Deque (Double Ended Queue)

Deque is an interface that extends Queue and represents a double-ended queue. Elements can be added or removed from both
ends.
ArrayDeque and LinkedList are implementations of the Deque interface.

Methods of Deque:

addFirst(E e): Adds an element to the front.


addLast(E e): Adds an element to the end.
removeFirst(): Removes and returns the first element.
removeLast(): Removes and returns the last element.
peekFirst(): Retrieves but does not remove the first element.
peekLast(): Retrieves but does not remove the last element.

Example:

import java.util.*;

public class DequeExample {


public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();

deque.addFirst("First");
deque.addLast("Second");
deque.addFirst("Zero");

System.out.println("Deque: " + deque); // Output: [Zero, First, Second]

You might also like