I want to create a TreeMap in Java with a custom sort order. The sorted keys which are string need to be sorted according to the second character. The values are also string.
Sample map:
Za,FOO
Ab,Bar
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.
You can use a custom comparator like this:
Sample:
Note that this simply assumes that the
Stringhas a character at index 1. It throwsStringIndexOutOfBoundsExceptionif it doesn’t.Alternatively, you can also use this comparison:
This subtraction “trick” is broken in general, but it works fine here because the subtraction of two
charwill not overflow anint.The
substringandcompareTosolution above is more readable, though.See also: