Mak
Mak

Reputation: 1078

How to sort Map by value in desc and key in natural order at the same time in Java 8

There is any way to sort a Map by key and value at the same operation. Map has value {hover=1, solar=1, waterproof=3, storage=1, battery=2}

So after sorting value should be

{waterproof=3, battery=2, hover=1, solar=1, storage=1}

I am trying to as

    Map mp = map.entrySet().stream()
            .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (newValue,oldValue) -> oldValue, LinkedHashMap::new))
        //.sorted(Map.Entry.comparingByKey())           
        //.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        //(newValue,oldValue) -> oldValue, LinkedHashMap::new))
            ;

Upvotes: 3

Views: 975

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100209

Create a comparator chain using thenComparing:

Map mp = map.entrySet().stream()
            .sorted(Collections.reverseOrder(Map.Entry.<String, Integer>comparingByValue())
                    .thenComparing(Map.Entry.comparingByKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (newValue, oldValue) -> oldValue, LinkedHashMap::new));

Note that in this case, you need to specify explicit type arguments for the first comparator, as compiler cannot infer types in such a complex case.

Upvotes: 3

Related Questions