Mark As Completed Discussion

Queue

The Queue interface in Java represents a collection of elements that supports insertion, removal, and retrieval operations. It follows the First-In-First-Out (FIFO) order, where the element that is inserted first is the first one to be removed.

To use the Queue interface, you need to import the java.util.Queue package.

Here's an example that demonstrates the usage of the Queue interface:

TEXT/X-JAVA
1import java.util.LinkedList;
2import java.util.Queue;
3
4public class Main {
5
6  public static void main(String[] args) {
7    // Create a queue
8    Queue<String> queue = new LinkedList<>();
9
10    // Adding elements to the queue
11    queue.add("Alice");
12    queue.add("Bob");
13    queue.add("Charlie");
14
15    // Printing the queue
16    System.out.println("Queue: " + queue);
17
18    // Accessing the front element of the queue
19    String frontElement = queue.peek();
20    System.out.println("Front element: " + frontElement);
21
22    // Removing elements from the queue
23    String removedElement = queue.poll();
24    System.out.println("Removed element: " + removedElement);
25
26    // Printing the updated queue
27    System.out.println("Updated Queue: " + queue);
28
29    // Checking if the queue is empty
30    boolean isEmpty = queue.isEmpty();
31    System.out.println("Is Queue empty: " + isEmpty);
32
33    // Checking the size of the queue
34    int size = queue.size();
35    System.out.println("Size of the queue: " + size);
36  }
37
38}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment