Searching...
Sunday, 22 June 2014

Java Priority Queue Example

07:47
Priority Queue introduced as part of Java 1.5 and it is an unbounded queue based on a priority heap.

Elements in the queues are in natural ordering or by a comparator provided by at queue construction time.

It does not allow null values.

Example:


Here is one simple example to create a PriorityQueue to store order details and our priority is to process premium orders first.

package com.vinod;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueTest {

public static void main(String[] args) {

// Creating Priority Queue and inserting objects
Comparator<String> pqc = new PQueueComparator();
Queue<String> orderQueue = new PriorityQueue<String>(100, pqc);
orderQueue.add("order number 1");
orderQueue.add("order number 2 premium");
orderQueue.add("order number 3");
orderQueue.add("order number 4");
System.out.println("Order details after insertion");
for (String orderDetail : orderQueue) {
System.out.println(orderDetail);
}
System.out.println("priority order " + orderQueue.poll());
}

}

class PQueueComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (s1.length() < s2.length()) {
return 1;
}
if (s1.length() > s2.length()) {
return -1;
}

return 0;
}

}

Ouput:

Order details after insertion
order number 2 premium
order number 1
order number 3
order number 4
priority order order number 2 premium

0 comments: