简体   繁体   English

如何对HashMap进行降序排序(基于值),并同时保持字典顺序(基于键)?

[英]How to sort a HashMap in descending order (based on the value) and keep the lexigraphy order (based on key) at the same time?

The code below can get the descending order based on value, but I have no idea of how to keep the lexigraphy order. 下面的代码可以基于值获得降序,但是我不知道如何保持笔法顺序。

If two elements have the same value, eg hello-3 and hi-3 , then hello-3 should in front of hi-3 since e is in the front of i . 如果两个元素具有相同的值,例如hello-3hi-3 ,则hello-3应该在hi-3因为ei的前面。

//get the descending order based on value (frequency)

public static <K, V extends Comparable<? super V>> Map<K, V> 
sortByValue( Map<K, V> map ) {
    List<Map.Entry<K, V>> list =
    new LinkedList<Map.Entry<K, V>>( map.entrySet() );

    Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {
            // it should be o2 compareTo o1, since I need descending order
            return (o2.getValue()).compareTo( o1.getValue() );
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}

after sorting your first Map add this : 在对您的第一个地图进行排序之后,添加以下内容:

Map result = new TreeMap<>(Collections.reverseOrder()); 地图结果=新的TreeMap <>(Collections.reverseOrder());

and then do this : 然后执行以下操作:

result .putAll(list); 结果.putAll(list);

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

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