The task here is that i get input string, for example 'tree' and sort it based on frequency, Output should be 'eetr'/'eert'
, since e repeats 2 times and t,r frequency is 1.
i have this code, what is does it traverses the string, puts all characters in string in Hashmap with their frequencies and a priority queue is used for sorting them in descending order, after which the result is taken in a string builder,
but i need some help in understanding the lambda function used in the parameter of priority queue. Here is my function.
public String frequencySort(String s) // lets assume that input string is "tree"
{
HashMap<Character,Integer> map = new HashMap<>();
for(char c:s.toCharArray())
{
map.put(c,map.getOrDefault(c,0) + 1);
} // now after this my HashMap will have values (t,1),(r,1),(e,2)
PriorityQueue<Character> maxHeap = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a)); //my question is about this constructor in priority queue, There are just two input parameters , how subtracting two things will help in sorting ??
maxHeap.addAll(map.keySet()); // i guess the keyset is now 't,r,e' but constructor has only 2 parameters, what is going on ? How will the constructor help in setting the sorting behaviour of prioroty queue?
StringBuilder result = new StringBuilder();
while(maxHeap.isEmpty())
{
char current = maxHeap.remove();
for(int i=0;i < map.get(current);i++)
{
result.append(current);
}
}
}
can someone explain me the flow using example 'tree' in the function