我有一个HashMap<Character, Integer>
,我想按照整数的升序将值放入PriorityQueue
。我无法想办法做到这一点。我有一个可以保存值的Node
类,所以:PriorityQueue<Node>
。
答案 0 :(得分:1)
在这种情况下,我不会使用Map
....
撰写您自己的Pair
/ Node
课程,其中包含您的Character
和Integer
,并将此课程设为Comparable
。
您可以阅读Comparable
here。
在您的Node类中,您必须实现compareTo
方法,如下所示:
public int compareTo(Node o) {
return this.idd - o.idd ;
}
其中id是包含整数的变量。
像这样,您可以将它们放在SortedSet
中TreeSet
或您在问题中提到的PriorityQueue
答案 1 :(得分:0)
代码示例:
HashMap<Character, Integer> h = new HashMap<Character, Integer>();
h.put('z',30);
h.put('e',10);
h.put('b',20);
h.put('c',20);
List<Map.Entry> a = new ArrayList<Map.Entry>(h.entrySet());
Collections.sort(a,
new Comparator() {
public int compare(Object o1, Object o2) {
Map.Entry e1 = (Map.Entry) o1;
Map.Entry e2 = (Map.Entry) o2;
return ((Comparable) e1.getValue()).compareTo(e2.getValue());
}
});
for (Map.Entry e : a) {
System.out.println(e.getKey() + " " + e.getValue());
}
输出(按OP要求的整数值排序):
e 10
b 20
c 20
z 30