Queue in Java

Java 8Object Oriented ProgrammingProgramming

The queue interface is provided in java.util package and it implements the Collection interface. The queue implements FIFO i.e. First In First Out. This means that the elements entered first are the ones that are deleted first.

A program that demonstrates queue in Java is given as follows −

Example

 Live Demo

import java.util.LinkedList;
import java.util.Queue;
public class Example {
   public static void main(String[] args) {
      Queue<Integer> q = new LinkedList<>();
      q.add(6);
      q.add(1);
      q.add(8);
      q.add(4);
      q.add(7);
      System.out.println("The queue is: " + q);
      int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);
}
}

Output

The queue is: [6, 1, 8, 4, 7]
The element deleted from the head is: 6
The queue after deletion is: [1, 8, 4, 7]
The head of the queue is: 1
The size of the queue is: 4

Now let us understand the above program.

Five elements are inserted in the queue. Then the queue is displayed. The code snippet that demonstrates this is given as follows −

Queue<Integer> q = new LinkedList<>();
q.add(6);
q.add(1);
q.add(8);
q.add(4);
q.add(7);
System.out.println("The queue is: " + q);

The element from the head of the queue is deleted and it is displayed. Then the size of the queue is displayed. The code snippet that demonstrates this is given as follows −

int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);
raja
Updated on 27-Jun-2020 12:56:12

Advertisements