How to sort HashMap in ascending order
I have the following Key: Value pairs.
A56:A64=9, A65:A73=9, A2:A8=7, A49:A55=7, A20:A26=7, A9:A19=11, A43:A48=6, A27:A42=16
I want to sort them in ascending order. I tried to use TreeMap
but got this:
{A20:A26=7, A27:A42=16, A2:A8=7, A43:A48=6, A49:A55=7, A56:A64=9, A65:A73=9, A9:A19=11}
A2: A8 = 7 should come first, but it comes third.
Please let me know how I can fix this.
source to share
TreeMap
String
will use the default lexicographic string order for key (this is the natural order for String
s) unless you provide your own Comparator in the constructor.
A2: A8 appears after A20: A26 when using lexicographic order.
Your comparator is likely to be split String key into 4 pieces (for example, A20:A26
will be divided into A
, 20
, A
and 26
), and compare each pair of parts separately, using integer comparison to whole units.
source to share