Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a HashMap in ascending order [duplicate]

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 an ascending order. I tried using a TreeMap but a 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 be first, but it is coming third.

Please let me know how I can fix this.

like image 470
Umesh Kumar Avatar asked Mar 18 '23 15:03

Umesh Kumar


1 Answers

TreeMap for a String key would use String lexicographical order by default (that's the natural ordering for Strings), unless you supply your own Comparator in the constructor.

A2:A8 comes after A20:A26 when using lexicographical order.

Your comparator would probably have to split the String key into 4 parts (for example, A20:A26 would be split to A, 20, A and 26) and compare each pair of parts separately, using integer comparison for the integer parts.

like image 95
Eran Avatar answered Mar 24 '23 14:03

Eran