Queue Interface in Java

  • September 16, 2022
  • Java
java thread class

The Queue interface extends the Collection interface and is present in java.util package is used to hold the elements about to be processed in FIFO (First In First Out) order. It is an ordered list of objects that can only be used to insert elements at the end of the list and delete elements from the beginning of the list (i.e., it adheres to the FIFO or First-In-First-Out principle). Queues provide additional insertion, removal, and inspection operations in addition to basic Collection operations. 

public interface Queue extends Collection
Method of Queue interface:
Method Description
boolean add(E e)Inserts the specified element into this queue as soon as possible without violating capacity constraints, returning true on success and throwing an IllegalStateException if no space is currently available.
E element()The head of this queue is retrieved but not removed.
boolean offer(E e)Inserts the specified element into this queue as soon as possible without violating capacity constraints.
E peek()Retrieves the head of this queue but does not remove it, or returns null if the queue is empty.
E poll()This method retrieves and removes the queue’s head, or returns null if the queue is empty.
E remove()This function retrieves and removes the queue’s head.

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

public class Coderz {

	public static void main(String[] args)
	    Scanner sc= new Scanner(System.in);
		Queue<Integer> q
			= new LinkedList<>();

		for (int i = 0; i < 5; i++)

		// Display contents of the queue.
		System.out.println("Elements of queue "
						+ q);

		// To remove the head of queue.
		int removedele = q.remove();
		System.out.println("removed element "
						+ removedele);


		// To view the head of queue
		int head = q.peek();
		System.out.println("head of queue "
						+ head);

		// Rest all methods of collection
		// interface like size and contains
		// can be used with this
		// implementation.
		int size = q.size();
		System.out.println("Size of queue "
						+ size);
Elements of queue [2, 3, 4, 5, 6]
removed element 2
[3, 4, 5, 6]
head of queue 3
Size of queue 4

Note: also read about the SortedMap Interface in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.



Leave a Reply

Your email address will not be published. Required fields are marked *