java - PriorityQueue, insert with priority -


i'd know how can add value priorityqueue specific value.

i have map<integer, integer> // element -> value , i'd insert elements priorityqueue value priority.

for example:

map{1=0, 3=5265, 5=22375, 7=4202, 9=233, 11=351, 13=119} 

should have order in queue:

{1, 13, 9, 11, 7, 3, 5} 

priorityqueue expects elements comparable each other. doesn't explicitly track priority of each element itself. compares them each other. means you'll need elements , priorities queue in pairs.

one way add map.entrys directly , create queue custom comparator.

priorityqueue<map.entry<integer, integer>> queue =     new priorityqueue<>(comparator.comparing(entry -> entry.getvalue()));  queue.addall(map.entryset()); 

another way create simple class holding both values implements comparable. like:

class elementpriority implements comparable<elementpriority> {     int element;     int priority;      @override public int compareto(elementpriority other) {         return integer.compare(this.priority, other.priority);     } } 

or if want hacky combine each pair of ints long holding both values. if store priorities in big end elements should naturally sort priority.

priorityqueue<long> queue = new priorityqueue<>();  map.foreach((element, priority) -> {     queue.add((priority & 0xffffffffl) << 32 | (element & 0xffffffffl)); }); 

this highly dubious, hey, heck.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -