我正在尝试接收字符串列表并将它们添加到具有键和值的优先级队列中。键是单词,值是单词的字符串值。然后我需要先对字符串值最高的队列进行排序。优先级队列不允许我添加 2 个值。
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;
}
最佳答案
问题
PriorityQueue
可以在它的每个节点中存储单个对象。所以你想做的事情不能按原样完成。
但是您可以将两个对象组合在一个类中,然后使用 PriorityQueue
。
您要么需要提供 Comparator
或依靠 natural ordering通过实现 Comparable
界面。
解决方案
创建一个包含
String
和int
成员的类。public class Entry { private String key; private int value; // Constructors, getters etc. }
实现
Comparable
接口(interface)并将比较委托(delegate)给String
。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()); } }
使用此类构建
PriorityQueue
。PriorityQueue<Entry> q = new PriorityQueue<>();
添加如下元素。
q.add(new Entry(strings.get(x), calculateStringValue(strings.get(x))));
希望这对您有所帮助。
关于java - 将键和值添加到优先级队列中并在 Java 中按键排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872664/