How to sort a HashMap in ascending order [duplicate]
Asked Answered
H

1

5

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.

Hemingway answered 15/12, 2014 at 8:18 Comment(5)
"ascending order" of what? Key, values?Creditor
Please show your code.Templet
you can use Collections.sort with a comparator. so you can decide how it will compareBrasil
Default comparator sorts strings in lexicographical order. What you need is called numerical order. Check out the link in my previous comment if you want to implement custom comparator for hashmapGinaginder
I want in ascending order of KeysHemingway
S
7

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.

Shanta answered 15/12, 2014 at 8:20 Comment(1)
I splited the key on ":" then took the first parameter and replaced the "A", which gave me numeric value and normal TreeMap worked there.thanksHemingway

© 2022 - 2024 — McMap. All rights reserved.