问题
I am trying to take in a List of strings and add them into a Priority Queue with Key and Value. The Key being the word and the value being the string value of the word. Then I need to sort the queue with the highest string value first. The priority queue is not letting me add 2 values.
public static List<String> pQSortStrings(List<String> strings) {
PriorityQueue<String, Integer> q = new PriorityQueue<>();
for (int x = 0; x < strings.size(); x++) {
q.add(strings.get(x),calculateStringValue(strings.get(x)));
}
return strings;
}
回答1:
Problem
PriorityQueue can store a single object in it's each node. So what you are trying to do can not be done as it is.
But you can compose both objects in a single class and then use the PriorityQueue
.
You would either need to supply a Comparator or rely on natural ordering by implementing Comparable interface.
Solution
Create a class which has
String
andint
as it's members.public class Entry { private String key; private int value; // Constructors, getters etc. }
Implement
Comparable
interface and delegate comparison toString
.public class Entry implements Comparable<Entry> { private String key; private int value; public Entry(String key, int value) { this.key = key; this.value = value; } // getters @Override public int compareTo(Entry other) { return this.getKey().compareTo(other.getKey()); } }
Build the
PriorityQueue
using this class.PriorityQueue<Entry> q = new PriorityQueue<>();
Add elements as following.
q.add(new Entry(strings.get(x), calculateStringValue(strings.get(x))));
Hope this helps.
回答2:
Using Java-8
PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>((a, b)->b.getValue()-a.getValue());
to add a new Entry
queue.offer(new AbstractMap.SimpleEntry<>("A", 10));
来源:https://stackoverflow.com/questions/29872664/add-key-and-value-into-an-priority-queue-and-sort-by-key-in-java