I have to implement Priority Queue using MultiMap. I use MultiMap from Google Collections.
The following code creates a MultiMap and adds few elements into it.
Multimap<Integer, String> multimap = HashMultimap.create();
multimap.put(5,"example");
multimap.put(1,"is");
multimap.put(1,"this");
multimap.put(4,"some");
Now my problem is how to write the pop method?
I think that there should be a for loop and it should be iterating through MultiMap.
The lowest key should be the highest priority, so in C++ I would set a pointer to the first element and increment it. How to do it in Java?
The
HashMultimapyou’re using won’t give you any help in efficiently selecting the lowest element. Instead use aTreeMultimap(also in Google Collections) which lets you specify an ordering and iterate through the items in the list in that order. For instance:You’ll notice that this always prints out entries in priority order, so to get the first-priority element you can just do
multimap.entries().iterator().next()(assuming you know the map has at least one element).See the TreeMultimap documentation for more information.