A basic queue is a collection of elements with a front end and rear end. Some of the other types of queue’s are listed below.
PriorityQueue:
A queue with priority value associated with it. It dequeued according to the
priority. Generally, higher priority is dequeued first.
ArrayDeque :
This implementation of queue can be resizable. The elements can be added or removed at both front and back
ends.
The java
implementations of both queues are given below.
1.Priority
Queue implementation in java:
This program uses the built in
packages java.util.PriorityQueue and java.util.Queue.
Steps:
- · Develop a class with main()
function.
- · Create an object for Queue class.
- · Insert the data elements to the
queue by add() function.
- · Deque the elements until the last element
and print the queue elements.
Program:
import
java.util.PriorityQueue;
import
java.util.Queue;
public
class PriorityQueueEg {
public static void main(String[] args) {
Queue<Integer> priorityQueue1 =
new PriorityQueue<>();
// Enqueue elements
priorityQueue1.add(310);
priorityQueue1.add(130);
priorityQueue1.add(253);
priorityQueue1.add(454);
priorityQueue1.add(364);
// printing the queue elements
System.out.println("The elements
in the PriorityQueue is: " + priorityQueue1);
while (!priorityQueue1.isEmpty()) {
System.out.println("The
Removed element is: " + priorityQueue1.poll());
}
}
}
Output:
C:\raji\blog>javac
PriorityQueueEg.java
C:\raji\blog>java
PriorityQueueEg
The
elements in the PriorityQueue is: [130, 310, 253, 454, 364]
The Removed
element is: 130
The Removed
element is: 253
The Removed
element is: 310
The Removed
element is: 364
The Removed
element is: 454
Next
implementation is given as follows.
ArrayDeque
implementation in java:
This implementation uses the built
in packages java.util.ArrayDeque and java.util.Deque.
Steps:
- · write a class with main() function.
- · Queue class object is created as integer.
- · Enque(insert) the data elements to
the queue by add() function.
- · Delete the elements until the last element
and print the queue elements.
Program:
import
java.util.ArrayDeque;
import
java.util.Deque;
public
class ArrayDequeEg {
public static void main(String[] args) {
Deque<Integer> deque1 = new
ArrayDeque<>();
// Enqueue(adding) elements at the end
deque1.addLast(231);
deque1.addLast(551);
deque1.addLast(300);
deque1.addLast(677);
// The elements in deque is displayed
here
System.out.println("ArrayDeque:
" + deque1);
// Dequeue(remove) the elements from the front
while (!deque1.isEmpty()) {
System.out.println("Removed
element: " + deque1.pollFirst());
}
}
}
Output:
C:\raji\blog>javac
ArrayDequeEg.java
C:\raji\blog>java
ArrayDequeEg
ArrayDeque:
[231, 551, 300, 677]
Removed
element: 231
Removed
element: 551
Removed
element: 300
Removed
element: 677
These are
the other queue implementation in java. Keep coding!!!
No comments:
Post a Comment