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>.
Asked
Active
Viewed 641 times
1
Jake Sellers
- 2,350
- 2
- 21
- 40
-
1possible duplicate http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java – Abubakkar Dec 05 '12 at 05:36
-
2Use a `SortedMap` (for example, `TreeMap`) instead: http://docs.oracle.com/javase/6/docs/api/java/util/SortedMap.html – Yuushi Dec 05 '12 at 05:38
-
I looked at that thread before posting, but I am not trying to sort the map itself(which is complicated and pretty much impossible due to the nature of hashmaps), but select them in an ordered manner. – Jake Sellers Dec 05 '12 at 05:39
-
yuushi, I would use a treemap or linked hash map if I had a choice :( – Jake Sellers Dec 05 '12 at 05:41
-
is Node class created by you or u have edit/subclass access to the Node class? – Pranalee Dec 05 '12 at 05:48
-
It is my own class, it holds a character and an integer. – Jake Sellers Dec 05 '12 at 05:51
2 Answers
1
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
Frank
- 16,476
- 7
- 38
- 51
-
ok, implemented comparable and overrode compareTO so that it returns -1 for less than, 0 for equal numbers, and 1 if greater than. – Jake Sellers Dec 05 '12 at 06:04
-
1OK, now just put the nodes in a sorted collection and see the magic happen. – Frank Dec 05 '12 at 06:28
-
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. – Jake Sellers Dec 05 '12 at 06:35
-
1The priorityqueue will sort automaticly on insert...if it does not you made a mistake when implementing comparable... beware of generics – Frank Dec 05 '12 at 06:43
0
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
xagyg
- 9,562
- 2
- 32
- 29