简体   繁体   English

首先用值对 hashmap 进行排序,然后在 java 中排序

[英]Sorting a hashmap first with values then keys in java

Hello guys i have a hash map like a:1,c:2,d:3,b:2 and i want to sort it like d:3,b:2,c:2,a:1, descending in values and alphabetical order in keys how can i do it i would be grateful for any help thanks! Hello guys i have a hash map like a:1,c:2,d:3,b:2 and i want to sort it like d:3,b:2,c:2,a:1, descending in values and按键中的字母顺序我该怎么做我将不胜感激任何帮助谢谢!

Sort the following in descending order of values then keys.按值的降序排序以下内容,然后是键。 I amended the list to make it more interesting.我修改了列表以使其更有趣。

Map<String, Integer> map = Map.of("a", 8, "b", 2, "c", 4, "d",
                8, "e", 3, "f", 4, "g", 7, "h", 1, "i", 5, "j", 2);

First define a Comparator to use in sorting the Map entries.首先定义一个Comparator器,用于对Map条目进行排序。 Each entry is represented by the Map.Entry class.每个条目由Map.Entry class 表示。 That class offers methods comparingByValue() and comparingByKey() . class 提供了方法 compareByValue comparingByValue()和 compareByKey comparingByKey()

The following code says, first sort by value , then by the key .下面的代码说,首先按value排序,然后按key排序。 These are sorted in natural order except the following reversed() method says reverse the sorting of all comparators prior.这些按自然顺序排序,但以下reversed()方法表示反转所有比较器的排序。 So the values will be sorted in reversed order and the keys in alphabetical order.因此, values将按相反顺序排序, keys按字母顺序排序。

Comparator<Entry<String, Integer>> comp = Entry
        .<String, Integer>comparingByValue().reversed()
        .thenComparing(Entry.comparingByKey());

This streams the existing map's entrys and applies the comparator to the sort method.这会流式传输现有地图的条目并将比较器应用于排序方法。 It then collects them in a linked hashMap to preserve the order.然后它将它们收集到链接的 hashMap 中以保留订单。 The merge function does not play a part in this but is syntactically required.合并 function 不参与其中,但在语法上是必需的。

Map<String, Integer> lhmap =
        map.entrySet().stream().sorted(comp)
                .collect(Collectors.toMap(Entry::getKey,
                        Entry::getValue,
                        (a, b) -> a,      // merge function
                        LinkedHashMap::new));

lhmap.entrySet().forEach(System.out::println);

That code prints:该代码打印:

a=8
d=8
g=7
i=5
c=4
f=4
e=3
b=2
j=2
h=1

A HashMap is not necessarily ordered, and in fact does not guarantee that the key value pair orders wil lremain constant over time. HashMap不一定是有序的,实际上也不能保证键值对的顺序会随着时间的推移保持不变。 From the docs:从文档:

Hash table based implementation of the Map interface. Hash 基于表的 Map 接口的实现。 This implementation provides all of the optional map operations, and permits null values and the null key.此实现提供所有可选的 map 操作,并允许 null 值和 null 密钥。 (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.特别是,它不保证订单会随着时间的推移保持不变。

If you want a sorted map, use a NavigableMap or SortedMap .如果您想要排序的 map,请使用NavigableMapSortedMap There are a few options.有几个选项。 TreeMap is probably the simplest. TreeMap可能是最简单的。

A Red-Black tree based NavigableMap implementation.基于红黑树的 NavigableMap 实现。 The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. map 是根据其键的自然顺序排序的,或者由 map 创建时提供的比较器排序,具体取决于使用的构造函数。

So to create a map with the keys in descending alphabetical order something like this should do the tick:因此,要创建一个 map ,其键按字母降序排列,如下所示:

Comparator<String> comparator = new Comparator<>() {
    @Override
    public int compare(String o1, String o2) {      
        return o2.compareTo(o1);
    }
};

TreeMap<String, Integer> treeMap = new TreeMap<>(comparator);

This answer is using java 8 streams.这个答案是使用 java 8 个流。

//LinkedHashMap preserve the ordering of elements in which they are inserted //LinkedHashMap 保留插入元素的顺序

LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
    unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
            .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
     
    System.out.println("Reverse Sorted Map   : " + reverseSortedMap); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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