1

Let's say that I have a TreeMap Alphabet in Java:

Map<String, Integer> alphabet = new TreeMap<String, Integer>();

and we put the letter as a key and its number as a value in the map without sorting them at all:

alphabet.put("a", 1);
alphabet.put("c", 3);
alphabet.put("b", 2);
alphabet.put("u", 21);
alphabet.put("l", 12);
.
.
.
alphabet.put("y", 25);
alphabet.put("z", 26);

And I want to order them by descending value (from 26 to 1). I want to print something like this:

z   26
y   25
x   24
.
.
.
d   4
c   3
b   2
a   1

Could not find anything simple enough without overcomplicating the code for this specific example.

I will use this for just understanding the logic behind sorting Maps, so I can continue solving another task for homework. Thanks

  • Unless you do it just for training, ordering by value is a bad idea though ordering in sorted map is designed to be based on keys, not values – Alex Salauyou May 16 '19 at 12:24
  • `TreeMap` is sorted based on its keys, not its values, so it doesn't help you here. If you're using Java 8, there's an easy way to sort a map by its values. It's one of the answers in the linked duplicate, and here's how it's used for your example: https://ideone.com/7EAJPE – nickb May 16 '19 at 12:25

0 Answers0