Jake Sellers
Jake Sellers

Reputation: 2439

Sorting values in a HashMap

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

Upvotes: 1

Views: 647

Answers (2)

xagyg
xagyg

Reputation: 9711

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

Upvotes: 0

Frank
Frank

Reputation: 15631

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

Upvotes: 1

Related Questions