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
It's very similar to wordCount
example in Scala
. But it counts words in a string but your program counts letters in a word. very similar.
However, the map output will be as follow:
(t,1), (r,1), (e,2)
The map.get(b) - map.get(a)
is just used as comparator. If map.get(b) - map.get(a)
be negative which means map.get(b) < map.get(a)
and results to order before a. If be positive means map.get(b) > map.get(a)
and results to order after a. If be zero, they are equal.
See Javadoc for PriorityQueue : An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.