0

Update the HashMap according to the values in a stream of inputs in descending order.

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

When I print it in descending order, it will give output as :

{c=3, b=2, a=1}

And When I add this

map.put("a", map.get("a") + 10);

it should print as :

{a=11, c=3, b=2}
svvc
  • 1
  • currently it print as you said, what really you expect? – Mustafa Poya Dec 01 '20 at 15:04
  • Get the `EntrySet`, add it to a `List`, `sort` that `List` however you want, `print` _that_ `List` (and format it to look like a `Map`).# – BeUndead Dec 01 '20 at 15:12
  • HashMap has no order in Java. There is a same question: [link](https://stackoverflow.com/questions/8119366/sorting-hashmap-by-values) – imraklr Dec 01 '20 at 15:14

1 Answers1

0

HashMaps have no order. NavigableMaps have order, but only based on the key. LinkedHashMaps iterate (and thus print) in insertion order.

Having a map’s toString() do what you want is not available in the JDK.

However, you could print via code what you want by streaming the entries, sorting by the negative of the value, then joining a string version of the entries together.

Such code could be within an overridden toString() method if you extended HashMap.

Bohemian
  • 412,405
  • 93
  • 575
  • 722