我正在尝试获取字符串列表并将它们添加到带有键和值的优先级队列中。键是单词,值是单词的字符串值。然后我需要首先对具有最高字符串值的队列进行排序。优先级队列不允许我添加 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;
}
Problem
PriorityQueue http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html可以在其每个节点中存储单个对象。所以你想做的事情不能按原样完成。
但是您可以将这两个对象组合在一个类中,然后使用PriorityQueue
.
您需要提供Comparator https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html或依靠自然排序 https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html通过实施Comparable http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html界面。
Solution
-
创建一个类,其中包含String
and int
因为它是会员。
public class Entry {
private String key;
private int value;
// Constructors, getters etc.
}
-
实施Comparable
接口和委托比较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))));
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)