Manipulate map using different ways?

35 views Asked by At

I am hoping to find an elegant way of sorting a map by value first and then by the key.

For example:

B | 50

A | 50

C | 50

E | 10

D | 100

F | 99

I have the following code:

// Making the map into a list first
List<Map.Entry<String, Integer>> sortingList = new LinkedList<>(processMap.entrySet()); 

// Create a comparator that would compare the values of the map
Comparator<Map.Entry<String, Integer>> c = Comparator.comparingInt(Map -> Map.getValue());

// Sort the list in descending order
sortingList.sort(c.reversed());

I don't need the result to be map again, so this is sufficient, however, my result is:

D | 100

F | 99

B | 50

A | 50

C | 50

E | 10

I would like to sort not just by value, but also by the key, so the result becomes:

D | 100

F | 99

A | 50

B | 50

C | 50

E | 10

I had researched some possible solutions, but the problem is, my values need to be in descending, but my key has to be ascending...

Hoping if anyone can help me.

1

There are 1 answers

0
AudioBubble On

Try this:

Comparator<Map.Entry<String, Integer>> c = Comparator.comparing(Map.Entry<String, Integer>::getValue)
                                                     .reversed()
                                                     .thenComparing(Map.Entry::getKey);