创建一个按Java中的Hashmap值排序的优先级队列

时间:2017-03-08 22:02:23

标签: java hashmap priority-queue comparator

我正在尝试将哈希映射中的键(它是类的静态变量)playerToBook添加到按值排序的优先级队列中,并且我在行上收到错误

PriorityQueue<Integer> maxBooksList = new PriorityQueue<>(playerToBook.size(), comparator);

说PriorityQueue不能应用于比较器。

public static PriorityQueue<Integer> playerWithMaxBooks() {

        Comparator<HashMap.Entry<Integer, Integer>> comparator = new fCompare();
        PriorityQueue<Integer> maxBooksList = new PriorityQueue<>(playerToBook.size(), comparator);
        Iterator it = playerToBook.entrySet().iterator();

        while (it.hasNext()) {

            HashMap.Entry pair = (HashMap.Entry) it.next();
            maxBooksList.add((Integer)pair.getKey());
        }

        return maxBooksList;
    }

    public static class fCompare implements Comparator<HashMap.Entry<Integer, Integer>>
    {
        @Override
        public int compare(HashMap.Entry<Integer, Integer> e1, HashMap.Entry<Integer, Integer> e2)
        {
            if (e1.getValue() < e2.getValue())
            {
                return -1;
            }
            if (e1.getValue() > e1.getValue())
            {
                return 1;
            }
            return 0;
        }
    }

请帮忙!

0 个答案:

没有答案