How to add a single map entry to priority queue

僤鯓⒐⒋嵵緔 提交于 2019-12-10 10:34:51

问题


At the moment I have to add the whole map, as shown in the last line.

PriorityQueue<Map.Entry<String, Integer>> sortedCells = new PriorityQueue<Map.Entry<String, Integer>>(3, new mem());
    Map<String,Integer> pn = new HashMap<String,Integer>();
    pn.put("hello", 1);
    pn.put("bye", 3);
    pn.put("goodbye", 8);
    sortedCells.addAll(pn.entrySet());

What if I just wanted to add

("word" 5)

If i do

sortedCells.add("word",5)

I get an argument error.

How can I add a single element?


回答1:


You should add a Map.Entry object and not just ("word", 5) because the generic type of your priority queue is Map.Entry<String, Integer>. In this case you should probably create your own Map.Entry class:

final class MyEntry implements Map.Entry<String, Integer> {
    private final String key;
    private Integer value;

    public MyEntry(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public Integer getValue() {
        return value;
    }

    @Override
    public Integer setValue(Integer value) {
        Integer old = this.value;
        this.value = value;
        return old;
    }
}

In your code you can now call:

sortedCells.add(new MyEntry("word",5));

If you don't want to implement your own entry you could use AbstractMap.SimpleEntry:

sortedCells.add(new AbstractMap.SimpleEntry<String, Integer>("word",5));


来源:https://stackoverflow.com/questions/35045451/how-to-add-a-single-map-entry-to-priority-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!