How do I use a Priority Queue

0 votes
How do I get a PriorityQueue to sort on what I want it to sort on?
May 19, 2018 in Java by Parth
• 4,640 points
1,041 views

2 answers to this question.

0 votes

Using lambda expression

PriorityQueue<String> priorityQueue=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> priorityQueue =
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
        
priorityQueue = new PriorityQueue<String>(5, Comparator.comparing(String::length));
       
priorityQueue.add("Apple");
priorityQueue.add("PineApple");
priorityQueue.add("Custard Apple");
        while (priorityQueue.size() != 0)
        {
            System.out.println(priorityQueue.remove());
        }
    }
answered May 19, 2018 by sharth
• 3,370 points
0 votes

Use the constructor overload which takes a Comparator<? super E> 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 offerhave 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 PriorityQueuewhich 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<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = 
            new PriorityQueue<String>(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<String>
{
    @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


answered Oct 10, 2018 by Sushmita
• 6,920 points

Related Questions In Java

0 votes
1 answer

How do I fix a NullPointerException?

When you declare a reference variable (i.e. ...READ MORE

answered Apr 13, 2018 in Java by Parth
• 4,640 points
970 views
0 votes
1 answer

How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

answered Apr 19, 2018 in Java by Rishabh
• 3,620 points
1,211 views
0 votes
2 answers

How do I convert an input stream into a byte array

You could probably try this if you ...READ MORE

answered Aug 29, 2019 in Java by Sirajul
• 59,230 points
3,888 views
0 votes
2 answers

How do I rename a file using Java

// File (or directory) with old name File ...READ MORE

answered Oct 5, 2018 in Java by Sushmita
• 6,920 points
851 views
0 votes
2 answers

Ho do I Iterate through a HashMap which contains duplicate values

for (Map.Entry<String, String> item : params.entrySet()) { ...READ MORE

answered Jul 24, 2018 in Java by samarth295
• 2,220 points
5,325 views
0 votes
2 answers

Performing Iteration over each entry in a 'Map'

In Java 8 you can do it ...READ MORE

answered Oct 24, 2018 in Java by Sushmita
• 6,920 points
1,127 views
0 votes
2 answers
0 votes
1 answer

How can I Sort an ArrayList in Java

You can sort the ArrayList in 2 ...READ MORE

answered Apr 23, 2018 in Java by sharth
• 3,370 points
880 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,230 points
2,358 views
0 votes
2 answers

How can I get the filenames of all files in a folder which may or may not contain duplicates

List<String> results = new ArrayList<String>(); File[] files = ...READ MORE

answered Sep 12, 2018 in Java by Sushmita
• 6,920 points
1,941 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP