简体   繁体   中英

Sort Hashmap keys by numerical value descending order

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?

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.

您可以使用TreeMap ,然后在其上调用descendingMap() ,它基本上返回一个具有键的反向排序的映射

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

}

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

您可以将TreeMap与允许您指定Comparator的构造函数一起使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM