Search code examples
javalambdahashmappriority-queue

How to initialize a HashMap with max Heap using Lambda in Java


In Java, initialization of a hash map with a min heap as the value:

Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();

Initialization of a max heap using lambda can be like:

PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);

However, how to initialize a hash map with a max heap using lambda?

This definitly doesn't work.

Map<Integer, PriorityQueue<Integer>((a, b) -> b - a)> map = new HashMap<>();

Solution

  • This does not "initialise of a hash map with a min heap as the value".

    Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
    

    This creates a HashMap, whose keys are integers, and whose values are PriorityQueue<Integer>s.

    A PriorityQueue<Integer> can act like a max heap or a min heap, depending on the Comparator<Integer> that you pass into its constructor. This means that map above can contain both max heaps and min heaps.

    map.put(1, new PriorityQueue<>(Comparator.naturalOrder())); // a min heap is associated with the key 1
    map.put(2, new PriorityQueue<>(Comparator.reverseOrder())); // a max heap is associated with the key 2
    

    Note that you should not use subtraction (i.e. (a, b) -> b - a) to compare integers. See this post for more info.

    With that cleared out of the way, we can make a HashMap that only contains min heaps, or only contains max heaps, by declaring our own MinHeap and MaxHeap types.

    MinHeap and MaxHeap can inherit from PriorityQueue, and calling PriorityQueue's constructor with an appropriate Comparator argument.

    class MinHeap<T extends Comparable<T>> extends PriorityQueue<T> {
        public MinHeap() {
            super(Comparator.naturalOrder());
        }
    }
    
    class MaxHeap<T extends Comparable<T>> extends PriorityQueue<T> {
        public MaxHeap() {
            super(Comparator.reverseOrder());
        }
    }
    

    Now, a HashMap<Integer, MinHeap<Integer>> only contains min heaps as values, and a HashMap<Integer, MaxHeap<Integer>> only max heaps as values.

    Map<Integer, MinHeap<Integer>> minHeapMap = new HashMap<>();
    Map<Integer, MaxHeap<Integer>> maxHeapMap = new HashMap<>();