0

My custom sort for PriorityQueue does not print in the way I wanted. I insert words with their frequencies in priorityQueue and when I poll them I should get the word with highest frequency and if frequencies of both words are same, I should get word which is smallest in lexicographical order. Somehow my custom priorityQueue does not work in that way.

import java.util.*;

class Pair {
    String word;
    int freq;

    Pair(String word, int frequency) {
        this.word = word;
        this.freq = freq;
    }
}

class SortCustom implements Comparator<Pair> {
    public int compare(Pair a, Pair b) {
        if(a.freq == b.freq)
            return a.word.compareTo(b.word);
        return b.freq - a.freq;
    }
}

public class HelloWorld {
    public static void main(String[] args) {
        PriorityQueue<Pair> queue = new PriorityQueue<>(new SortCustom());
        queue.add(new Pair("leaf",1));
        queue.add(new Pair("i",2));
        queue.add(new Pair("love",2));
        queue.add(new Pair("code",1));
        while(!queue.isEmpty()){
            System.out.println(queue.poll().word);
        }
    }
}

Output I get:

code
i
leaf
love

Output I want:

i
love
code
leaf

1 Answer 1

1

It took me a while, but this doesn't have anything to do with PriorityQueue. The issue is the constructor of Pair:

    Pair(String word,int frequency){
        this.word=word;
        this.freq=freq;
    }

This should be

    Pair(String word,int freq) {
        this.word=word;
        this.freq=freq;
    }

You were always setting freq to its original value of 0, not to the argument passed to the constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey Louis,Thank you so much,i was not able to figure out the typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.