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}
3
  • currently it print as you said, what really you expect? Commented Dec 1, 2020 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).# Commented Dec 1, 2020 at 15:12
  • HashMap has no order in Java. There is a same question: link Commented Dec 1, 2020 at 15:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.