简体   繁体   中英

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 .

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

and then do this :

result .putAll(list);

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