a queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and the removal of entities from the other end of the sequence. By convention, the end of the sequence at which elements are added is called the back, tail, or rear of the queue, and the end at which elements are removed is called the head or front of the queue, analogously to the words used when people line up to wait for goods or services.

The operation of adding an element to the rear of the queue is known as enqueue, and the operation of removing an element from the front is known as dequeue. Other operations may also be allowed, often including a peek or front operation that returns the value of the next element to be dequeued without dequeuing it.

Real life example: when you visit BANK for deposit money into your account, you may face a long line out there. You can’t do your work at the first position of line; you need to wait for your turn. Which person first in the line he/she will do their job first. This is a perfect example of queue order.

The operations of a queue make it a first-in-first-out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed.

Methods

add() -> inserts new element into queue from rear.
poll () -> removes existing element from front of the stack.
peek() -> gets front of the queue element without removing(deleting).
isEmpty() -> checks stack is empty or not.
source: wikipedia.org

In order to use the functionalities of Queue, we need to use classes that implement it:

  • ArrayDeque
  • LinkedList
  • PriorityQueue
  1. Write a code, to perform queue operations – add, remove(poll),peek element.
import java.util.Queue;
import java.util.LinkedList;
 
class queue1 {
 public static void main(String[] args) {
        // Creating Queue using the LinkedList class
        Queue<Integer> que = new LinkedList<>();
 
        // adds elements to the Queue
        que.add(20);
        que.add(10);
        que.add(30);
        que.add(50);
 
      
        System.out.println(“Queue: ” + que);
        System.out.println(“queue length is “+que.size());
        System.out.println(“Accessed Element: ” + que.peek());
 
        // Remove elements from the Queue
        que.poll();
        System.out.println(“Queue: ” + que);
        System.out.println(“queue length is “+que.size());
        System.out.println(“Accessed Element: ” + que.peek());
 
        // Remove elements from the Queue
        que.poll();
        System.out.println(“Queue: ” + que);
        System.out.println(“queue length is “+que.size());
        System.out.println(“Accessed Element: ” + que.peek());
 
 
    }
}
output