I have a HashMap<Character, Integer> and I'd like to place the values into a PriorityQueue in ascending order of the integers. I'm having trouble thinking of a way to do this. I have a Node class that can hold the values, so: PriorityQueue<Node>.
2 Answers
I would not use a Map in this case....
Write your own Pair/Node class that holds your Character and Integer and make this class implement Comparable.
You can read up on Comparable here.
In your Node Class you will have to implement the compareTo method, somthing like this:
public int compareTo(Node o) {
return this.idd - o.idd ;
}
Where id is the variable holding your integer.
Like this you can put them in a SortedSet like a TreeSet or the PriorityQueue you mention in your question
4 Comments
Jake Sellers
ok, implemented comparable and overrode compareTO so that it returns -1 for less than, 0 for equal numbers, and 1 if greater than.
Frank
OK, now just put the nodes in a sorted collection and see the magic happen.
Jake Sellers
ya I decided to put them all in the priority queue and then sort. Collections.sort() does not seem to work with my priority queue though :( ok, I re-read the doc on priorityQueue, looks like it automagically orders itself.
Frank
The priorityqueue will sort automaticly on insert...if it does not you made a mistake when implementing comparable... beware of generics
Code example:
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());
}
Output (ordered by integer value as required by OP):
e 10
b 20
c 20
z 30
SortedMap(for example,TreeMap) instead: docs.oracle.com/javase/6/docs/api/java/util/SortedMap.html