首页 > Java 中 PriorityQueue 如何转换成 Map

Java 中 PriorityQueue 如何转换成 Map

现在有一个 PriorityQueue,里面的元素是 Map 的 Entry,如下:

PriorityQueue<Entry<String, int>> priorityQueue = new PriorityQueue<Entry<String, int>>();
Map<String, int> map = new HashMap<String, int>();

我想要用这些 Entry 建一个 HashMap。现在的实现方法如下:

for(Entry<String, int> entry: priorityQueue)
  map.put(entry.getKey(), entry.getValue());

后来我写了另一种实现:

map.putAll((Map)priorityQueue);

但编译器提示这种类型转换不能保证正确性。

我想请问一下,有其他的效率能高过我当前实现方法的实现方式吗?


首先:Entrykey值value值都必须是类型,而你定义的value是int基本数据类型。这个错误编译器会给出提示。正确的定义如下:

        PriorityQueue<Entry<String, Integer>> priorityQueue = new PriorityQueue<Entry<String, Integer>>();
        Map<String, Integer> map = new HashMap<String, Integer>();

然后是队列PriorityQueue转换成集合Map,这样做存在一个问题是:当队列中存在相同的对象时,转换到Map中这个对象只会有一个,下面的put动作可以解释这个原因:

map.put(entry.getKey(), entry.getValue());

最后解决问题的办法,你可以常识将优先级队列PriorityQueue换成TreeMap,两者都有自定义排序的功能。同时在转换时也就很容易了。

【热门文章】
【热门文章】