简体   繁体   中英

Sort HashMap descending by value and ascending by key at the same time

Consider the following hashmap:

HashMap<String, Double> cityScoreMap = new HashMap<>();

with values such as

CityB, 5.0
CityC, 10.0
CityA, 5.0

I need to sort the hashmap descendingly by values, but if the values are equal, sort ascendingly by keys:


CityC, 10.0 (highest value)
CityA, 5.0 (comes before CityB, because A < B)
CityB, 5.0 (comes after CityA)

So far tried to sort separately by keys, then by values, but I don't trust this method. What are some good ways to do it, other than creating even more hashmaps?

The easiest way to achieve this sort of a Map is with stream. You have to implement a Comparator.

Map<String, Double> cityScoreMap = new HashMap<>();
cityScoreMap.put("CityB", 5.0);
cityScoreMap.put("CityC", 10.0);
cityScoreMap.put("CityA", 5.0);

Comparator<Map.Entry<String, Double>> descendingValueAscendingKeyComparator = (entry1, entry2) -> {
        //natural ordering of numbers is ascending, so comparing entry2 value to entry1 value makes for descending order
        int cmp = entry2.getValue().compareTo(entry1.getValue());
        if (cmp == 0) {
            //if comparison result is zero, that means values are equal, so we are comparing keys
            //we are comparing entry1 to entry2 keys for ascending order, which is natural for string
            return entry1.getKey().compareTo(entry2.getKey());
        }
        return cmp;
    };
cityScoreMap.entrySet()//get the set of entries in the map
            .stream()//stream the entries
            .sorted(descendingValueAscendingKeyComparator)//sort the entries with the supplied comparator
            .forEach(entry -> System.out.println(entry.getKey() + ", " + entry.getValue()));//print to verify ordering

Comparators define ordering of elements, which might be different from their natural order. This comparator defines the ordering of entries(key-value pairs) in your map - first by value descending, then by key ascending. Here the entries are just printed, so you can see the ordering, but you can also store them in another structure, which can keep their order - LinkedHashMap for example, whatever might be your actual need.

You should read up on the Comparator and Comparable interfaces starting with the javadoc.

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