4

How can I sort HashMap keys by their numerical value? Currently, in the natural ordering it looks like this:

1 10 13 2 26 29

I want it to look like this:

29 26 13 10 2 1

Any ideas?

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Maurice
  • 6,413
  • 13
  • 51
  • 76

5 Answers5

10

A HashMap cannot be sorted. If you require sorted keys, take a look at the TreeMap. In order to get the reversed ordering you want, you would have to provide a custom Comparator:

class ReversedOrdering implements Comparator<Integer> {
    public int compare(Integer lhs, Integer rhs) {
        // compare reversed
        return rhs.compareTo(lhs);
    }
}

Edit I just stumbled across Collections.reverseOrder() which does just what you want: It gives you a Comparator that reverses the natural ordering of objects that implement Comparable. This saves you the hassle of writing a comparator yourself.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • I realised my key was not numerical anymore. Thanks for the info though! – Maurice Aug 29 '11 at 09:02
  • @Maurice: I have added a simpler solution to get the reverse of a natural ordering (the type of the keys does not matter: if the implement `Comparable`, you can reverse the ordering this way). – Björn Pollex Aug 29 '11 at 18:58
6

You can use a TreeMap and then call descendingMap() on it which basically returns a map with the reverse ordering of the keys

A Null Pointer
  • 2,261
  • 3
  • 26
  • 28
0

Try below code it works fine and based on order flag it will sort ascending or descending.

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Rais.Alam
 * @date Dec 12, 2012
 */
public class HelloWorld
{
    public static void main(String[] args)
    {
        final boolean order = true;
        try
        {

            Map<Integer, String> map = new TreeMap<Integer, String>(
                    new Comparator<Integer>()
                    {

                        @Override
                        public int compare(Integer first, Integer second)
                        {

                            if (order)
                            {

                                return second.compareTo(first);
                            }
                            else
                            {
                                return first.compareTo(second);

                            }
                        }
                    });

            map.put(2, "v");
            map.put(3, "h");
            map.put(4, "e");
            map.put(1, "a");

            System.out.println(map);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
Rais Alam
  • 6,970
  • 12
  • 53
  • 84
0

HashMap doesn't sort anything. Use a TreeMap instead if you want to keep the keys sorted.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
0

You could use TreeMap with the constructor that lets you specify a Comparator.

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169