How can I sort HashMap keys by their numerical value? Currently, in the natural ordering it looks like this:
1 10 13 2 26 29
I want it to look like this:
29 26 13 10 2 1
Any ideas?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
HashMapcannot be sorted. If you require sorted keys, take a look at theTreeMap. In order to get the reversed ordering you want, you would have to provide a customComparator:Edit I just stumbled across
Collections.reverseOrder()which does just what you want: It gives you aComparatorthat reverses the natural ordering of objects that implementComparable. This saves you the hassle of writing a comparator yourself.