How to use the lambda expression in the value of Hashmap
I want to put a priority queue in the value part of a HashMap and I want to define the lambda of the queue by myself. I know where to put the lambda when creating the priority queue itself, but I'm confused that where to put the lambda if I want to put in the PQ which is in the value part of a HashMap.
Is the code below correct and the best way to do it? (We want to make the priority queue max heap)
Map<String, PriorityQueue<Integer>> map = new HashMap<>((Integer b, Integer a) -> a.CompareTo(b));
Solution 1:
You need to create the PriorityQueue with the Comparator every time you insert a key.
Map<String, PriorityQueue<Integer>> map = new HashMap<>();
map.put("key", new PriorityQueue<>((Integer b, Integer a) -> a.compareTo(b)));
Side note the Comparator can be simplified to
map.put("key", new PriorityQueue<>(Comparator.reverseOrder()));