1

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>.

Jake Sellers
  • 2,350
  • 2
  • 21
  • 40

2 Answers2

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
  • 1
    OK, 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
  • 1
    The 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