I wish to make a max heap in Java,but couldn't understand this. can someone explain this to me
Question: Given a string, sort it in decreasing order based on the frequency of characters.
Input="tree"
Output Expected:"eetr"
So I need a max heap using Priority Queue,but i didn't get how this code works. How the declaration of Priority Queue works?
public class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
pq.addAll(map.entrySet());
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
Map.Entry e = pq.poll();
for (int i = 0; i < (int)e.getValue(); i++)
sb.append(e.getKey());
}
return sb.toString();
}
}
so want to know how this
new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
thing works for making a Priority Queue.