Java Queue and PriorityQueue Overview
Java Queue and PriorityQueue Overview
The interface Queue is available in the [Link] package and does extend the
Collection interface. It is used to keep the elements that are processed in the
First In First Out (FIFO) manner. It is an ordered list of objects, where
insertion of elements occurs at the end of the list, and removal of elements
occur at the beginning of the list.
Being an interface, the queue requires, for the declaration, a concrete class,
and the most common classes are the LinkedList and PriorityQueue in Java.
Implementations done by these classes are not thread safe. If it is required
to have a thread safe implementation, PriorityBlockingQueue is an available
option.
Method Description
boolean It is used to insert the specified element into this queue and return true
add(object) success.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns null i
queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue, or return
if this queue is empty.
Features of a Queue
The following are some important features of a queue.
PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that
gives us a way for processing the objects on the basis of priority. It is already
described that the insertion and deletion of objects follows FIFO pattern in
the Java queue. However, sometimes the elements of the queue are needed
to be processed according to the priority, that's where a PriorityQueue
comes into action.
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
FileName: [Link]
import [Link].*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
[Link] = id;
[Link] = name;
[Link] = author;
[Link] = publisher;
[Link] = quantity;
}
public int compareTo(Book b) {
if(id>[Link]){
return 1;
}else if(id<[Link]){
return -1;
}else{
return 0;
}
}
}
public class LinkedListExample {
public static void main(String[] args) {
Queue<Book> queue=new PriorityQueue<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
//Adding Books to the queue
[Link](b1);
[Link](b2);
[Link](b3);
[Link]("Traversing the queue elements:");
//Traversing queue elements
for(Book b:queue){
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
[Link]();
[Link]("After removing one book record:");
for(Book b:queue){
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]
y);
}
}
}
Output:
Method Description
boolean It is used to insert the specified element into this deque and return
add(object) upon success.
Object poll() It is used to retrieve and removes the head of this deque, or returns n
this deque is empty.
Object It is used to retrieve, but does not remove, the head of this deque.
element()
Object peek() It is used to retrieve, but does not remove, the head of this deque, or ret
null if this deque is empty.
Object The method returns the head element of the deque. The method does
peekFirst() remove any element from the deque. Null is returned by this method, w
the deque is empty.
Object The method returns the last element of the deque. The method does
peekLast() remove any element from the deque. Null is returned by this method, w
the deque is empty.
Boolean Inserts the element e at the front of the queue. If the insertion is succes
offerFirst(e) true is returned; otherwise, false.
Object Inserts the element e at the tail of the queue. If the insertion is succes
offerLast(e) true is returned; otherwise, false.
ArrayDeque class
We know that it is not possible to create an object of an interface in Java.
Therefore, for instantiation, we need a class that implements the Deque
interface, and that class is ArrayDeque. It grows and shrinks as per usage. It
also inherits the AbstractCollection class.
1. import [Link].*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. [Link](str);
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
Output:
1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity
){
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class ArrayDequeExample {
15. public static void main(String[] args) {
16. Deque<Book> set=new ArrayDeque<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","For
ouzan","Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to Deque
22. [Link](b1);
23. [Link](b2);
24. [Link](b3);
25. //Traversing ArrayDeque
26. for(Book b:set){
27. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+
" "+[Link]);
28. }
29. }
30. }
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike
array, we can store n-number of elements in it as there is no size limit. It is a
part of Java Collection framework since Java 1.2. It is found in
the [Link] package and implements the List interface, so we can use all the
methods of List interface here.
The Iterators returned by the Vector class are fail-fast. In case of concurrent
modification, it fails and throws the ConcurrentModificationException.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.
S Constructor Description
N
S Method Description
N
3) addElement() It is used to append the specified component to the end of this vect
increases the vector size by one.
8) containsAll() It returns true if the vector contains all of the elements in the spe
collection.
9) copyInto() It is used to copy the components of the vector into the specified array
13) equals() It is used to compare the specified object with the vector for equality.
15) forEach() It is used to perform the given action for each element of the Iterable
all elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
18) indexOf() It is used to get the index of the first occurrence of the specified eleme
the vector. It returns -1 if the vector does not contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the given v
at the specified index.
21) iterator() It is used to get an iterator over the elements in the list in proper sequ
23) lastIndexOf() It is used to get the index of the last occurrence of the specified eleme
the vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in p
sequence.
25) remove() It is used to remove the specified element from the vector. If the v
does not contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are present i
specified collection.
27) removeAllElemen It is used to remove all elements from the vector and set the size o
ts() vector to zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argu
from the vector.
30) removeIf() It is used to remove all of the elements of the collection that satisf
given predicate.
31) removeRange() It is used to delete all of the elements from the vector whose ind
between fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of applyin
operator to that element.
33) retainAll() It is used to retain only that element in the vector which is contained i
specified collection.
34) set() It is used to replace the element at the specified position in the vector
the specified element.
35) setElementAt() It is used to set the component at the specified index of the vector t
specified object.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the spe
Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elem
in the list.
40) subList() It is used to get a view of the portion of the list between fromI
inclusive, and toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vect
correct order.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
Output:
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Output:
Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
Java Stack
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One
of them is the Stack class that provides different operations such as push,
pop, search, etc.
The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the stack and
pop operation removes an element from the top of the stack. Let's see how
they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the [Link] package and create an
object of the Stack class.
Or
1. Stack<type> stk = new Stack<>();
Where type denotes the type of stack like Integer, String, etc.
push(E item) E The method pushes (insert) an element onto the top of the stac
pop() E The method removes an element from the top of the stack
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without rem
it.
search(Objec int The method searches the specified object and returns the posit
t o) the object.
Syntax
Returns: The method returns true if the stack is empty, else returns false.
[Link]
1. import [Link];
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = [Link]();
[Link]("Is the stack empty? " + result);
11.// pushing elements into stack
[Link](78);
[Link](113);
[Link](90);
[Link](120);
16.//prints elements of the stack
[Link]("Elements in Stack: " + stk);
[Link] = [Link]();
[Link]("Is the stack empty? " + result);
20.}
21.}
Output:
Syntax
1. public E pop()
Let's implement the stack in a Java program and perform push and pop
operations.
[Link]
1. import [Link].*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. [Link]("stack: " + stk);
9. //pushing elements into the stack
[Link](stk, 20);
[Link](stk, 13);
[Link](stk, 89);
[Link](stk, 90);
[Link](stk, 11);
[Link](stk, 45);
[Link](stk, 18);
17.//popping elements from the stack
[Link](stk);
[Link](stk);
20.//throws exception if the stack is empty
[Link]
22.{
[Link](stk);
24.}
[Link] (EmptyStackException e)
26.{
[Link]("empty stack");
28.}
29.}
30.//performing push operation
[Link] void pushelmnt(Stack stk, int x)
32.{
33.//invoking push() method
[Link](new Integer(x));
[Link]("push -> " + x);
36.//prints modified stack
[Link]("stack: " + stk);
38.}
39.//performing pop operation
[Link] void popelmnt(Stack stk)
41.{
[Link]("pop -> ");
43.//invoking pop() method
[Link] x = (Integer) [Link]();
[Link](x);
46.//prints modified stack
[Link]("stack: " + stk);
48.}
49.}
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
Syntax
1. public E peek()
[Link]
1. import [Link];
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. [Link]("Apple");
9. [Link]("Grapes");
[Link]("Mango");
[Link]("Orange");
[Link]("Stack: " + stk);
13.// Access element from the top of the stack
[Link] fruits = [Link]();
15.//prints stack
[Link]("Element at top: " + fruits);
17.}
18.}
Output:
Suppose, o is an object in the stack that we want to search for. The method
returns the distance from the top of the stack of the occurrence nearest the
top of the stack. It uses equals() method to search an object in the stack.
Syntax
Returns: It returns the object location from the top of the stack. If it returns
-1, it means that the object is not on the stack.
[Link]
import [Link];
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
[Link]("Mac Book");
[Link]("HP");
[Link]("DELL");
[Link]("Asus");
[Link]("Stack: " + stk);
// Search an element
int location = [Link]("HP");
[Link]("Location of Dell: " + location);
}
}
Syntax
[Link]
1. import [Link];
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. [Link](22);
8. [Link](33);
9. [Link](44);
[Link](55);
[Link](66);
12.// Checks the Stack is empty or not
[Link] rslt=[Link]();
[Link]("Is the stack empty or not? " +rslt);
15.// Find the size of the Stack
[Link] x=[Link]();
[Link]("The stack size is: "+x);
18.}
19.}
Output:
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of
the stack using three different methods are as follows:
Syntax
1. Iterator<T> iterator()
Let's perform an iteration over the stack.
[Link]
1. import [Link];
2. import [Link];
3. public class StackIterationExample1
4. {
5. public static void main (String[] args)
6. {
7. //creating an object of Stack class
8. Stack stk = new Stack();
9. //pushing elements into stack
[Link]("BMW");
[Link]("Audi");
[Link]("Ferrari");
[Link]("Bugatti");
[Link]("Jaguar");
15.//iteration over the stack
[Link] iterator = [Link]();
[Link]([Link]())
18.{
[Link] values = [Link]();
[Link](values);
21.}
22.}
23.}
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Syntax
[Link]
1. import [Link].*;
2. public class StackIterationExample2
3. {
4. public static void main (String[] args)
5. {
6. //creating an instance of Stack class
7. Stack <Integer> stk = new Stack<>();
8. //pushing elements into stack
9. [Link](119);
[Link](203);
[Link](988);
[Link]("Iteration over the stack using forEach() Method:");
13.//invoking forEach() method for iteration over the stack
[Link](n ->
15.{
[Link](n);
17.});
18.}
19.}
Output:
Syntax
Returns: This method returns a list iterator over the elements, in sequence.
[Link]
1. import [Link];
2. import [Link];
3. import [Link];
4.
5. public class StackIterationExample3
6. {
7. public static void main (String[] args)
8. {
9. Stack <Integer> stk = new Stack<>();
[Link](119);
[Link](203);
[Link](988);
[Link]<Integer> ListIterator = [Link]([Link]());
[Link]("Iteration over the Stack from top to bottom:");
[Link] ([Link]())
16.{
[Link] avg = [Link]();
[Link](avg);
19.}
20.}
21.}
Output: