-2

I want to get the sorted key value pair on value, and if the values are equal, I wanna sort on keys asc.

I tried using PriorityQueue like following but I am getting null pointer for some reason. Please help me understand the issue and probably answer my query.

This is what I came up with, but unfortunately the output of the code is

PQ : [Hello, Yes]

Where as I was expecting

PQ : [No, Hello]

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>() {{
            put("Hello", 50);
            put("Yes", 50);
            put("No", 100);
        }};
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> {
            if (map.get(a).equals(map.get(b))) return a.compareTo(b);
            else return Integer.compare(map.get(b), map.get(a));
        });
        verifyPQ(map, pq);
        System.out.println(pq);
    }

    private static void verifyPQ(Map<String, Integer> map, PriorityQueue<String> pq) {
        for (String key : map.keySet()) {
            pq.add(key);
            if (pq.size() > 2) {
                pq.poll();
            }
        }
}
9
  • @pjs thanks for the recommendation, I have updated it according to your review Commented Feb 24, 2024 at 17:47
  • Your comparator doesn’t make much sense, nor does your assertion that you are both getting an NPE and unexpected output. Commented Feb 24, 2024 at 18:26
  • 1) that code is not throwing NullPointerException! 2) Does not compile/run as posted! 3) Using compare(map.get(b), map.get(a)) means that 100 comes before 50 so the "No" entry will be removed first; try compare(map.get(a), map.get(b)) Commented Feb 24, 2024 at 20:33
  • [ 4) be aware that a PriorityQueue only guarantees that the first element (head) ist sorted ] Commented Feb 24, 2024 at 20:38
  • 1
    you still didn't explain the "I am getting null pointer" ?? but code as posted is not running anyways !! Commented Feb 25, 2024 at 22:18

1 Answer 1

0

Why don't you use comparator instead of unnecessarily complicating things with priority queues?

If I have understood correctly, you want to sort by value in descending order and by key in ascending order.

Map<String, Integer> map = new HashMap<>();
map.put("Hello", 50);
map.put("Yes", 50);
map.put("No", 100);


map.entrySet()
   .stream()
   .sorted(Comparator.comparing(Entry<String,Integer>::getValue).reversed()
                     .thenComparing(Entry::getKey))
   .forEach(System.out::println);

If you only need the first two, just add a limit

map.entrySet()
   .stream()
   .sorted(Comparator.comparing(Entry<String,Integer>::getValue).reversed()
                     .thenComparing(Entry::getKey))
   .limit(2)
   .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Eritrean, I wanted to use PriorityQueue because, that is what I thought would help me to solve this with custom sorting order. But this helps a lot. Just out of curiosity, can we achieve this with PriorityQueue? if so, how?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.