Home > Back-end >  Initialize a Priority Queue with custom comparator, which is inside a HashMap
Initialize a Priority Queue with custom comparator, which is inside a HashMap

Time:12-16

Assume that I have a HashMap, where the value is of type PriorityQueue like:

HashMap<Integer, PriorityQueue<Integer>> someMap = new HashMap<>();

But how do I initialize this HashMap, if I need the PriorityQueue to have a custom comparator?

The actual comparator is much more complex, But for simplicity let's assume that I need the PriorityQueue to sort by reverse order, which I can do by:

PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());

Where and How should I define the comparator for the value in HashMap?

CodePudding user response:

The Comparator which PriorityQueue uses internally doesn't change its type anyhow.

A PriorityQueue<Integer> which uses the natural ordering, or Comparator.reverseOrder(), or for instance Comparator.nullsFirst(Comparator.reverseOrder()) (or any other Comparator) is still a PriorityQueue<Integer>. And you can store all these Queues in a map of type Map<Integer,PriorityQueue<Integer>>

You don't need to do anything special while instantiating the Map, just simply invoke the constructor new HashMap<>() as you did.

Map<Integer, Queue<Integer>> someMap = new HashMap<>();
        
Queue<Integer> pq1 = new PriorityQueue<>();
Queue<Integer> pq2 = new PriorityQueue<>(Comparator.reverseOrder());
Queue<Integer> pq3 = new PriorityQueue<>(Comparator.nullsFirst(Comparator.reverseOrder());
        
someMap.put(1, pq1);
someMap.put(2, pq1);
someMap.put(3, pq1);

Note

  • That generic type parameters like <Integer,Queue<Integer>> are meant to allow the compiler to verify that you're using the appropriate types. It is a compile-type mechanism for preventing problems like Heap-pollution, and it has nothing with how the memory would be allocated at Runtime.

  • You might be interested in reading What does it mean to "program to an interface"? to learn what are the benefits of using high-level abstractions like Map and Queue.

CodePudding user response:

The Answer in the question itself. You put the comparator inside the Priority Queue instance so.

HashMap<Integer, PriorityQueue<Integer>> someMap = new HashMap<>();
PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
someMap.put(1,queue);

that for initialization and when you put data in your queue you can use the same queue to put data.

  • Related