Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / How do I use a PriorityQueue?

How do I use a PriorityQueue?

August 20, 2021 by James Palmer

Use the constructor overload which takes a Comparator comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you’re not sure. (It’s pretty straightforward though.)
As has been said elsewhere: offer and add are just different interface method implementations. In the JDK source I’ve got, add calls offer. Although add and offer have potentially different behaviour in general due to the ability for offer to indicate that the value can’t be added due to size limitations, this difference is irrelevant in PriorityQueue which is unbounded.
Here’s an example of a priority queue sorting by string length:
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
public static void main(String[] args) {
Comparator comparator = new StringLengthComparator();
PriorityQueue queue = new PriorityQueue(10, comparator);
queue.add(“short”);
queue.add(“very long indeed”);
queue.add(“medium”);
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() – y.length(),
// which would be more efficient.
if (x.length() < y.length()) { return -1; } if (x.length() > y.length()) {
return 1;
}
return 0;
}
}

Here is the output:

short
medium
very long indeed

Java 8 solution
We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :
Using lambda expression
PriorityQueue pq=
new PriorityQueue(5,(a,b) -> a.length() – b.length());

Using Method reference
PriorityQueue pq=
new PriorityQueue(5, Comparator.comparing(String::length));

Then we can use any of them as:
public static void main(String[] args) {
PriorityQueue pq=
new PriorityQueue(5, (a,b) -> a.length() – b.length());
// or pq = new PriorityQueue(5, Comparator.comparing(String::length));
pq.add(“Apple”);
pq.add(“PineApple”);
pq.add(“Custard Apple”);
while (pq.size() != 0)
{
System.out.println(pq.remove());
}
}

This will print:
Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:
PriorityQueue pq = new PriorityQueue(5,
Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:
PriorityQueue pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue pq = new PriorityQueue(5,
Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:
default Comparator reversed() {
return Collections.reverseOrder(this);
}

offer() vs add()
As per the doc

The offer method inserts an element if possible, otherwise returning
false. This differs from the Collection.add method, which can fail to
add an element only by throwing an unchecked exception. The offer
method is designed for use when failure is a normal, rather than
exceptional occurrence, for example, in fixed-capacity (or “bounded”)
queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in