Java中的Lambda表达式如何帮助排序?帮我了解

问题描述

这里的任务是我得到输入字符串,例如'tree'并根据频率对其进行排序,输出应为'eetr'/'eert',因为e重复2次且t,r频率为1。

我有这段代码,它遍历字符串是什么,将所有字符及其频率放入Hashmap中,并使用优先级队列对它们进行降序排序,然后在字符串生成器中获取结果,

但是我需要一些帮助来理解优先级队列参数中使用的lambda函数。这是我的功能。

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,(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);
        }
    }

}

有人可以使用函数中的“树”示例向我解释流程吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)