Java Queue - The Coding Shala

Home >> Learn Java >> Java queue

Java Queue

In this post, we will discuss what is Java Queue and how to implement it in Java?

Java Queue is a part of Java Collections. Queues are an important data structures when we want to maintain the order. Queue works on FIFO(First in First Out) concept. The two important operations in queue is enqueue(insert) and dequeue(delete). 

Java Queue Implementation

The following java program explains the basic operations of the Java Queue: 

import java.util.LinkedList;
import java.util.Queue;

public class Main{
 public static void main(String[] args) {
  //initialize queue
  Queue<Integer> queue = new LinkedList<>();
  
  //Print Queue
  System.out.println("Queue is: "+queue);
  
  //push elements in Queue
  //we use add() and offer() method
     //the only difference between them is throwing exception
  queue.add(1);
  queue.add(2);
  queue.offer(3);
  queue.offer(4);
  System.out.println("Queue is: "+queue);
  
  //delete element
  //we use remove() and poll() method
  //difference is remove throws exception if queue is empty
  queue.remove();
  queue.poll();
  System.out.println("Queue is: "+queue);
  
  //see the head element
  //use element() and peek()
  //it does not remove the element only use to see
  System.out.println("First element of queue is: "+queue.element());
  queue.poll();
  System.out.println("First element of queue is: "+queue.peek());
  
  //size of queue
  //we use size() method
  System.out.println("Size of queue is: "+queue.size());
 }
}
Output: 

Queue is: []
Queue is: [1, 2, 3, 4]
Queue is: [3, 4]
First element of queue is: 3
First element of queue is: 4
Size of queue is: 1


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

Maximum Population Year LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala