java 按数值降序对 Hashmap 键进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7227753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:12:22  来源:igfitidea点击:

Sort Hashmap keys by numerical value descending order

javasortinghashmap

提问by Maurice

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

如何HashMap按键的数值对键进行排序?目前,按照自然顺序,它看起来像这样:

1 10 13 2 26 29

I want it to look like this:

我希望它看起来像这样:

29 26 13 10 2 1

Any ideas?

有任何想法吗?

回答by Bj?rn Pollex

A HashMapcannot 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:

AHashMap无法排序。如果您需要排序的键,请查看TreeMap. 为了获得您想要的反向排序,您必须提供自定义Comparator

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

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

编辑我刚刚偶然发现Collections.reverseOrder()它可以满足您的需求:它为您提供了一个Comparator反转实现的对象的自然顺序Comparable。这为您省去了自己编写比较器的麻烦。

回答by A Null Pointer

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

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

回答by Rais Alam

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

}

回答by Petar Minchev

HashMapdoesn't sort anything. Use a TreeMapinstead if you want to keep the keys sorted.

HashMap不排序任何东西。如果要保持键排序,请改用TreeMap

回答by Joonas Pulakka

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

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