I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some
However I want it
You need to implement your own Comparator
to do this kind of custom sorting. The default String.compareTo()
method seems to sort numbers before characters. When 0
in 20some
gets compared to s
in 3some
the 0
has a higher sort priority and therefore the whole word gets sorted in first.
What you would need to do is this: try to split you strings into the number and the character part. That's a hard task since those String
s can consist of many of those parts (or don't they?). You may use algorithms like Alphanum
, which Murtaza already showed to you.
If you want to implement it yourself, you could check, where the number part ends. Then parse it to an int
with Integer.parse()
. Compare int
parts if they exist in both String
s, then compare the rest. Well that may not be the most professional solution, but as a beginner you may want craft those things yourself to learn it.