Priority queue using Multimap – Java

I must use Multimap to implement priority queue I use Multimap in Google collections

Multimap<Integer,String> multimap = HashMultimap.create();

    multimap.put(5,"example");
    multimap.put(1,"is");
    multimap.put(1,"this");
    multimap.put(4,"some");

Now my question is how to write pop methods?

I think there should be a for loop, which should iterate through Multimap

The lowest key should be the highest priority, so in C I'll set the pointer to the first element and increment it How to do it in Java?

Solution

The hashmultimap you are using will not help you in effectively selecting the lowest element Instead, you use tree Multimap (also in Google collections), which allows you to specify the order and traverse the items in the list in order For example:

for (Map.Entry<Integer,String> entry : multimap.entries()) {
  System.out.println("Item " + entry.getValue() + " has priority " + entry.getKey();
}

You'll notice that this always prints the input in priority order, so to get the first priority element, you can execute Multimap entries(). iterator(). Next () (assuming you know that the map has at least one element)

For more information, see the treemultimap documentation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>