Using Collections to sort is nifty, a lot better for me than using Comparator since i have multiple values that are the same and i’d rather them not be just thrown out to the trash. But Collections has it’s own issue, it seems to think repeating numbers of groups of 2+ to be smaller than their actual smaller counter parts
Example have these keys and values(“katy 1″,”mark 9″,”john 2″,”alice 11″,”josiah 22″,”chris 44”) and it sorts them as follows
alice 11
katy 1
john 2
josiah 22
chris 44
mark 9
Instead of the correct order
katy 1
john 2
mark 9
alice 11
josiah 22
mark 44
How can i fix this?
Since you are passing strings, the collection has no way of telling how you want these strings to be interpreted (i.e. sort by the number present inside the string). You must be more explicit.
You have two options basically:
Option 1: Create a new data type to encapsulate a name and a number and implement comparison by number:
Then:
Option 2: Turn the string into a key-value pair and put it inside a
TreeMap, which automatically keeps the values sorted by key: