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 18, 2018 in Java by parth295
• 4,590 points
38 views

2 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 18, 2018 by sharth
• 3,310 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,820 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 parth295
• 4,590 points
56 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,520 points
59 views
0 votes
1 answer

How do I convert an input stream into a byte array

There is a simple solution without the ...READ MORE

answered Apr 25, 2018 in Java by developer_1
• 3,220 points
104 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,820 points
32 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,190 points
77 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,820 points
31 views
0 votes
1 answer

How can I convert an 'ArrayList<String> to 'String[]' in Java

List<String> list = new ArrayList<String>(); String[] array = ...READ MORE

answered Apr 20, 2018 in Java by Daisy
• 8,020 points
76 views
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,310 points
35 views
0 votes
1 answer

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

You can convert a String to int by using a function: int ...READ MORE

answered Apr 12, 2018 in Java by sharth
• 3,310 points
45 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,820 points
578 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.