开发者

Sort Hashmap keys by numerical value descending order

How can I sort HashMap keys by their numerical value? Currently, in the natural ordering it l开发者_运维技巧ooks like this:

1 10 13 2 26 29

I want it to look like this:

29 26 13 10 2 1

Any ideas?


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.


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


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


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


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();
        }
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜