Java Queue Example With Complete Understanding

The Queue interface is part of java.util package and extends the Collection interface. Here we have explained with Java Queue Example.

The Queue is a First In First Out (FIFO) data structure same as a queue in railway ticket counter, at metro station and movie hall etc.

It inserts elements at the end of the list and delete elements from the beginning of the list

The queue collection is order list of elements which is used to store the elements that are about to be processed by providing various operations like deletion, insertion etc.

Queue Data Structure

Java Queue

Here will discuss few important points about Java Queue:

  • Java Queue is ordered collection of elements.
  • Java Queue follows First In First Out (FIFO) principle to insert and remove elements. 
  • It supports all methods of Collection interface like insertion, deletion etc.
  • Important Queue implementations are LinkedList, PriorityQueue and ArrayBlockingQueue.
  • The Queues available in java.util package are Unbounded Queues
  • The Queues available in java.util.concurrent package are the Bounded Queues.
  • All Queues except the Deques will support insertion and deletion at the tail and head of the queue respectively. Deques will support element insertion and deletion at both ends.
  • Deques are not thread-safe.
  • BlockingQueue can not store null elements.
  • BlockingQueue can be used in multithreaded environment because they are thread-safe.
  • BlockingQueue are mostly used to perform the Producer/Consumer based problems.

Java Queue Class Diagram

Java Queue interface extends Collection interface.

Some Queue implementation classes are LinkedList, ArrayBlockingQueue, PriorityQueue, LinkedBlockingQueue, DelayQueue, PriorityBlockingQueue etc.

Java Queue Hierarchy

Methods in Queue

Some important methods of Queue interface

  1. add()- It is used to add elements at the tail of queue.
  2. peek()- It is used to view the head of queue without deleting it. It will return Null if the queue is empty.
  3. element()-  It is similar to peek(). It throws NoSuchElementException when queue is empty.
  4. remove()- It will remove and return the head of the queue. It will throw NoSuchElementException when queue is empty.
  5. poll()- This method returns and removes the head of the queue. It will return null if the queue is empty.
  6. size()- It will return the no. of elements present in the queue.
  7. offer(E e): It inserts the element into the queue if it is possible to do so . And returns true if inserted else false.

Java Queue Types

Java Queue implementations can be broadly categorize into the following two types

  • Bounded Queues
  • Unbounded Queues

Bounded Queues are queues which are limited or bounded by the size which means we need to provide the maximum size of the queue at the time of creation and can be used in concurrent environment without any inconsistency. Example ArrayBlockingQueue.

Unbounded Queues are queues which are not limited or bounded by the size which means we need not to provide the size of the queue and can not be used in concurrent environment because it can cause inconsistency. Example LinkedList.

Queue implementations which are available in java.util package are Unbounded Queues and Queues that are available in java.util.concurrent package are Bounded Queues.

Creating a Queue and Performing operations like Enqueue and Dequeue

Queue enqueue and dequeue operations:

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

public class QueueExample {
    public static void main(String[] args) {
        // Create and initialize a Queue using a LinkedList
        Queue<String> qu = new LinkedList<>();

        // Adding new elements to the Queue (The Enqueue operation)
        qu.add("Robin");
        qu.add("Roy");
        qu.add("Stal");
        qu.add("Arnab");
        qu.add("Micheal");

        System.out.println("Queue : " + qu);

        // Removing an element from the Queue using remove() (The Dequeue operation)
        // The remove() method throws NoSuchElementException if the Queue is empty
        String name = qu.remove();
        System.out.println("Removed from Queue : " + name + " | New Queue : " + qu);

        // Removing an element from the Queue using poll()
        // The poll() method is similar to remove() except that it returns null if the Queue is empty.
        name = qu.poll();
        System.out.println("Removed from Queue : " + name + " | New Queue : " + qu);
    }
}
# Output
Queue : [Robin, Roy, Stal, Arnab, Micheal]
Removed from Queue : Robin | New Queue : [Roy, Stal, Arnab, Micheal]
Removed from Queue : Roy | New Queue : [Stal, Arnab, Micheal]

Java Array to Queue

Here we will explain how to convert a Java array to Queue using β€œCollections.addAll()” method with example.

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

public class QueueExample {
    public static void main(String[] args) {
        // Create and initialize a Queue using a LinkedList
    	
    	String nums[] = {"one","two","three","four","five"};
    	Queue<String> queue = new LinkedList<>();
    	Collections.addAll(queue, nums);
    	System.out.println(queue);
    }
}
#Output
[one, two, three, four, five]

Java Queue to Array

Here we will see how to convert a Java Queue to a Java Array using toArray() method :

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
    	Queue<String> queue = new LinkedList<>();
    	queue.add("one");
    	queue.add("two");
    	queue.add("three");
    	queue.add("four");
    	queue.add("five");
    		
    	String strArray[] = queue.toArray(new String[queue.size()]);
    	System.out.println(Arrays.toString(strArray)); 
    }
}
#Output:
[one, two, three, four, five]

Queue add() operation

The add() method is used to insert new element into the queue. If it does insert operation successfully, it returns true value. Otherwise it will throw java.lang.IllegalStateException. Here is the java queue example with add() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

    	System.out.println(queue.add("one"));
    	System.out.println(queue.add("two"));
    	System.out.println(queue);
    	System.out.println(queue.add("three"));
    	System.out.println(queue);
    }
}
#Output
true
true
[one, two]
Exception in thread "main" java.lang.IllegalStateException: Queue full
	at java.util.AbstractQueue.add(AbstractQueue.java:98)
	at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
	at QueueExample.main(QueueExample.java:15)

Queue offer() operation

The offer() method is used to insert new element into the queue. If it does insert operation successfully then it will return true value. Otherwise it returns false value. Here is the java queue example with offer() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	
    	BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

    	System.out.println(queue.offer("one"));
    	System.out.println(queue.offer("two"));
    	System.out.println(queue);
    	System.out.println(queue.offer("three"));
    	System.out.println(queue);
    }
}
#Output
true
true
[one, two]
false
[one, two]

Queue remove() operation

The remove() method is used to delete an element from head of the queue. If it does delete operation successfully then it will return the head element of queue. Otherwise it will throw java.util.NoSuchElementException. Here is the java queue example with remove() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	
    	Queue<String> queue = new LinkedList<>();
    	queue.offer("one");
    	queue.offer("two");		
    	System.out.println(queue);		
    	System.out.println(queue.remove());
    	System.out.println(queue.remove());		
    	System.out.println(queue.remove());	
    }
}
#Output
[one, two]
one
two
Exception in thread "main" java.util.NoSuchElementException
	at java.util.LinkedList.removeFirst(LinkedList.java:270)
	at java.util.LinkedList.remove(LinkedList.java:685)
	at QueueExample.main(QueueExample.java:17)

Queue poll() operation

The poll() method is used to delete element from head of the queue. If it does delete operation successfully, it will return the head element of queue. Otherwise it will return β€œnull” value. Here is the java queue example with poll() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	Queue<String> queue = new LinkedList<>();
    	queue.offer("one");
    	queue.offer("two");		
    	System.out.println(queue);		
    	System.out.println(queue.poll());
    	System.out.println(queue.poll());		
    	System.out.println(queue.poll());
    }
}
#Output
[one, two]
one
two
null

Queue element() operation

The element() method is used to retrieve an element from head of queue without deleting it. If it does examine process successfully then it will return head element of queue. Otherwise it throws java.util.NoSuchElementException. Here is the java queue example with element() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	Queue<String> queue = new LinkedList<>();
    	queue.add("one");
    		
    	System.out.println(queue.element());
    	System.out.println(queue);
    	queue.clear();
    	System.out.println(queue.element());
    }
}
#Output
one
[one]
Exception in thread "main" java.util.NoSuchElementException
	at java.util.LinkedList.getFirst(LinkedList.java:244)
	at java.util.LinkedList.element(LinkedList.java:663)
	at QueueExample.main(QueueExample.java:16)

Queue peek() operation

The peek() method is used to get an element from head of the queue without deleting it. If it does examine process successfully then it will return head element of the queue. Otherwise it returns null value. Here is the java queue example with peek() operation.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
    	Queue<String> queue = new LinkedList<>();
    	queue.add("one");
    		
    	System.out.println(queue.peek());
    	System.out.println(queue);
    	queue.clear();
    	System.out.println(queue.peek());
    }
}
#Output
one
[one]
null

Iterating over a Queue in Java

The iteration order in the Queue Collection is same as the insertion order.

  • Iterate Queue by using Java 8 forEach() method.
  • Iterate Queue by using iterator().
  • Iterate Queue by using Java 8 forEachRemaining() and iterator() method.
  • Iterate Queue by using simple for-each loop.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
    	Queue<String> qu = new LinkedList<>();

        qu.add("Rocky");
        qu.add("Mike");
        qu.add("Fredy");
        qu.add("Robert");
        
        System.out.println("\n## Iterating over a Queue using iterator() ##");
        Iterator<String> quIterator = qu.iterator();
        while (quIterator.hasNext()) {
            String name = quIterator.next();
            System.out.println(name);
        }

        System.out.println("## Iterating over a Queue using Java 8 forEach() ##");
        qu.forEach(name -> {
            System.out.println(name);
        });

        System.out.println("\n## Iterating over a Queue using simple for-each loop ##");
        for(String name: qu) {
            System.out.println(name);
        }
        
        System.out.println("\n## Iterating over a Queue using iterator() and Java 8 forEachRemaining() ##");
        quIterator = qu.iterator();
        quIterator.forEachRemaining(name -> {
            System.out.println(name);
        });
    }
}
#Output

## Iterating over a Queue using iterator() ##
Rocky
Mike
Fredy
Robert
## Iterating over a Queue using Java 8 forEach() ##
Rocky
Mike
Fredy
Robert

## Iterating over a Queue using simple for-each loop ##
Rocky
Mike
Fredy
Robert

## Iterating over a Queue using iterator() and Java 8 forEachRemaining() ##
Rocky
Mike
Fredy
Robert

Conclusion

In this article we have learnt about basics of Queue and its various operations like peek(), poll() , element() etc. We have also learnt how to add elements to the Queue and how to delete an element from Queue.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply