Queue Collections in Java
Back to: Java Tutorials For Beginners and Professionals
Queue Collections in Java with Examples
In this article, I am going to discuss Queue Collections in Java with Examples. Please read our previous
article where we discussed Set Collections in Java with Examples. As part of this article, we are going to
discuss the following pointers in detail which are related to Java Queue Collections.
1. Queue Interface in Java
2. Classes that implement Queue Interface in Java
3. Methods of Queue Interface
4. Priority Queue Collection in Java
5. DeQueue Collection in Java
6. ArrayDeque Collection in Java
Queue Collections in Java
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, the first element is
removed first and the last element is removed at last. This interface is dedicated to storing all the elements
where the order of the elements matter.
The Queue interface of the Java collections framework provides the functionality of the queue data
structure. It extends the Collection interface. Since the Queue is an interface, we cannot provide the direct
implementation of it.
Classes that implement Queue Interface in Java:
In order to use the functionalities of Queue, we need to use classes that implement it:
1. Priority Queue
2. Dequeue
Methods of Queue Interface
1. add(): Inserts the specified element into the queue. If the task is successful, add() returns true, if not
it throws an exception.
2. offer(): Inserts the specified element into the queue. If the task is successful, offer() returns true, if
not it returns false.
3. element(): Returns the head of the queue. Throws an exception if the queue is empty.
4. peek(): Returns the head of the queue. Returns null if the queue is empty.
5. remove(): Returns and removes the head of the queue. Throws an exception if the queue is empty.
6. poll(): Returns and removes the head of the queue. Returns null if the queue is empty.
Priority Queue Collection in Java:
It implements the Queue interface. The PriorityQueue class provides the functionality of the heap data
structure. The PriorityQueue class provides the facility of using a queue. But it does not order the elements
in a FIFO manner. It is based on Priority Heap.
The elements of the priority queue are ordered according to the natural ordering, or by
a Comparator provided at queue construction time, depending on which constructor is used.
Creating Priority Queue
Syntax : PriorityQueue<Integer> numbers = new PriorityQueue<Integer>();
Here, we have created a priority queue without any arguments. In this case, the head of the priority queue
is the smallest element of the queue. And elements are removed in ascending order from the queue.
Example to demonstrate Priority Queue in Java
import [Link].*;
class PriorityQueueDemo
{
public static void main (String args[])
{
PriorityQueue < String > queue = new PriorityQueue < String > ();
[Link] ("Amit");
[Link] ("Vijay");
[Link] ("Karan");
[Link] ("Jai");
[Link] ("Rahul");
[Link] ("head:" + [Link] ());
[Link] ("head:" + [Link] ());
[Link] ("Iterating the queue elements:");
Iterator itr = [Link] ();
Iterator itr = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}
[Link] ();
[Link] ();
[Link] ("After removing two elements:");
Iterator < String > itr2 = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}
}
}
Output:
PriorityQueue Example with Complex Data type in Java:
import [Link];
import [Link];
class Employee implements Comparable < Employee >
{
private String name;
private double salary;
public Employee (String name, double salary)
{
[Link] = name;
[Link] = salary;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
[Link] = name;
}
public double getSalary ()
{
return salary;
}
public void setSalary (double salary)
{
[Link] = salary;
}
@Override public boolean equals (Object o)
{
if (this == o)
return true;
if (o == null || getClass () != [Link] ())
return false;
Employee employee = (Employee) o;
return [Link] ([Link], salary) == 0 && [Link] (name
}
@Override public int hashCode ()
{
return [Link] (name, salary);
}
@Override public String toString ()
{
return "Employee{" + "name='" + name + '\'' + ", salary=" + salary + '}';
}
// Compare two employee objects by their salary
@Override public int compareTo (Employee employee)
{
if ([Link] () > [Link] ())
{
return 1;
}
else if ([Link] () < [Link] ())
{
return 1;
}
else
{
return 0;
}
}
}
public class PriorityQueueDemo
{
public static void main (String[]args)
{
// Create a PriorityQueue
PriorityQueue < Employee > employeePriorityQueue = new PriorityQueue <> ();
// Add items to the Priority Queue
[Link] (new Employee ("Rajeev", 100000.00));
[Link] (new Employee ("Chris", 145000.00));
[Link] (new Employee ("Andrea", 115000.00));
[Link] (new Employee ("Jack", 167000.00));
/*
The compareTo() method implemented in the Employee class is used to determin
The compareTo() method implemented in the Employee class is used to determin
in what order the objects should be dequeued.
*/
while (![Link] ())
{
[Link] ([Link] ());
}
}
}
Output:
DeQueue Collection in Java
Deque is an acronym for “doubleended queue”. Java Deque Interface is a linear collection that supports
element insertion and removal at both ends. The class which implements this interface is ArrayDeque. It
extends the Queue interface. Deque is an interface and has two implementations: LinkedList and
ArrayDeque.
Creating a Deque
Syntax : Deque dq = new LinkedList();
Deque dq = new ArrayDeque();
Methods of Deque
1. addFirst(): Adds the specified element at the beginning of the deque. Throws an Exception if the
deque is full.
2. addLast(): Adds the specified element at the end of the deque. Throws an exception if the deque is
full.
3. offerFirst(): Adds the specified element at the beginning of the deque. Returns false if the deque is
full.
4. offerLast(): Adds the specified element at the end of the deque. Returns false if the deque is full.
5. getFirst(): Returns the first element of the deque. Throws an exception if the deque is empty.
6. getLast(): Returns the last element of the deque. Throws an exception if the deque is empty.
7. peekFirst(): Returns the first element of the deque. Returns null if the deque is empty.
8. peekLast(): Returns the last element of the deque. Returns null if the deque is empty.
9. removeFirst(): Returns and removes the first element of the deque. Throws an exception if the
deque is empty.
10. removeLast(): Returns and removes the last element of the deque. Throws an exception if the
deque is empty.
11. pollFirst(): Returns and removes the first element of the deque. Returns null if the deque is empty.
12. pollLast(): Returns and removes the last element of the deque. Returns null if the deque is empty.
13. push(): Adds an element at the beginning of the deque.
14. pop(): Removes an element from the beginning of the deque.
15. peek(): Returns an element from the beginning of the deque.
ArrayDeque Collection in Java:
The ArrayDeque class provides the facility of using deque and resizablearray. It inherits the
AbstractCollection class and implements the Deque interface. This is a special kind of array that grows and
allows users to add or remove an element from both sides of the queue. Array deques have no capacity
restrictions and they grow as necessary to support usage. Array Implementation of Deque
Syntax : Deque<String> animal1 = new ArrayDeque<String>();
Example to demonstrate ArrayDeque Collection in Java
import [Link];
import [Link];
class ArrayDequeDemo {
public static void main(String[] args) {
// Creating Deque using the ArrayDeque class
Deque<Integer> numbers = new ArrayDeque<>();
// add elements to the Deque
[Link](1);
[Link](2);
[Link](3);
[Link]("Deque: " + numbers);
// Access elements of the Deque
int firstElement = [Link]();
[Link]("First Element: " + firstElement);
int lastElement = [Link]();
[Link]("Last Element: " + lastElement);
// Remove elements from the Deque
int removedNumber1 = [Link]();
[Link]("Removed First Element: " + removedNumber1);
int removedNumber2 = [Link]();
[Link]("Removed Last Element: " + removedNumber2);
[Link]("Updated Deque: " + numbers);
}
}
Output:
In the next article, I am going to discuss Map Collections in Java with examples. Here, in this article, I try to
explain Queue Collections in Java with Examples and I hope you enjoy this Queue collection in Java with
Examples article.
Previous Lesson Next Lesson
Set Collections in Java Map Collections in Java
Leave a Reply
Your email address will not be published. Required fields are marked *
Comment *
Name*
Email*
Website
Post Comment
Java Basics
Java Features
Java Application Development Lifecycle
Environment Setup for Java
Creating First Java Program
Data Types in Java
Literals in Java
Type Casting in Java
Operators in Java
Variables in Java
Identifiers and Reserved Words in Java
Control Flow Statements in Java
Looping Statements in Java
Branching Statements in Java
Methods in Java
Java User Input and Output
Pass By Value and Pass By Reference in Java
Command Line Arguments in Java
Java OOPs
Object‐Oriented Programming in Java
Class and Objects in Java
Constructors in Java
Inner Classes in Java
Wrapper Classes in Java
Polymorphism in Java
Encapsulation in Java
Access Modifiers in Java
Inheritance in Java
Abstraction in Java
Abstract Classes and Abstract Methods in Java
Interface in Java
Association Composition and Aggregation in Java
Garbage Collection in Java
Final Keyword in Java
Static Keyword in Java
Java Exception Handling
Exception Handling in Java
Finally Block in Java
throw and throws keywords in Java
Custom Exception in Java
Exception Propagation in Java
Java Strings, Packages, JVM & IO Streams
String in Java
Java Packages
JVM Architecture
Java IO Stream
Byte Streams in Java
Character Streams in Java
Serialization and Deserialization in Java
Java Array, Collection & Generics
Array in Java
Multi Dimensional Arrays in Java
Java Collections Framework
List Collections in Java
Cursors of Collection Framework in Java
Set Collections in Java
Queue Collections in Java
Map Collections in Java
Sorting Collections in Java
Generics in Java
Java Multithreading
Multithreading in Java
Thread Class in Java
Thread Life Cycle in Java
Thread Priority in Java
Daemon Thread in Java
Thread Synchronization in Java
Inter Thread Communication in Java
Deadlock in Java
Multithreading Exercises in Java
Java Applet, AWT & Event Handling
Applet in Java
Graphics in Applet
Abstract Windows Toolkit ﴾AWT﴿ in Java
AWT Controls in Java
Event Handling in Java
Event Listener Interfaces in Java
Layout Manager in Java
Java Swings
Swings in Java
Swing Controls in Java
Swing Dialog Box in Java
Working with Image Menus and files in Java Swings
Working with Tables and Progress Bars in Java Swings
Java Enumeration
Enumeration in Java
JDBC in Java
JDBC in Java
JDBC Architecture
JDBC Drivers
Steps to Design JDBC Applications in Java
CRUD Operations in Java using JDBC
JDBC ResultSet
Prepared Statement in JDBC
Java Advanced Features
Internationalization in Java
Regular Expression in Java
Parallel Programming in Java
Reflection in Java
Date and Time API in Java
Java Calendar Class
Java [Link]﴾﴿ Method
How to work with JSON in Java
Java Interview Questions
Java Interview Questions and Answers
Java Popular Books
Most Recommended Java Books
Most Recommended Data Structure and Algorithms Books using Java
Most Recommended JDBC Books
Most Recommended Hibernate Books
Games
Ranked: Easiest and Toughest Card Games to Program
About Us Privacy Policy Contact [Link] Tutorial Angular Tutorials [Link] Core Blazor Tuturials
[Link] Core Tutorials [Link] MVC Tutorials [Link] Web API Tutorials C Tutorials
C#.NET Programs Tutorials C#.NET Tutorials Cloud Computing Tutorials
Data Structures and Algorithms Tutorials Design Patterns Tutorials
DotNet Interview Questions and Answers Core Java Tutorials Entity Framework Tutorials
JavaScript Tutorials LINQ Tutorials Python Tutorials SOLID Principles Tutorials SQL Server Tutorials
Trading Tutorials JDBC Tutorials Java Servlets Tutorials Java Struts Tutorials C++ Tutorials
JSP Tutorials MySQL Tutorials Oracle Tutorials [Link] Core Web API Tutorials HTML Tutorials
© Dot Net Tutorials | Website Design by Sunrise Pixel