Sorting hashmap based on keys

user1008697 picture user1008697 · Oct 22, 2011 · Viewed 133.4k times · Source

I have the following hashmap in java:

{B046=0.0, A061=3.0, A071=0.0, B085=0.0, B075=3.0, B076=9.0, B086=3.0, B095=0.0, B096=0.0, A052=0.0, B066=0.0, B056=9.0, B065=0.0, B055=9.0}

How should I go about sorting the hashmap such that the Alphabet, followed by the numerical figures are taken into account?

The resulting hashmap should look like this:

{A052=0.0,A061=3.0,A071=0.0,B046=0.0,B055=9.0,B056=9.0,B065=0.0,B066=0.0,B075=3.0,B076=9.0,B085=0.0,B086=3.0,B095=0.0,B096=0.0}

Appreciate the help!

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Oct 22, 2011

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.