0

I have this List<String>:

key.add("ss1");
key.add("s1");
...
key.add("s10");
key.add("s11");
...

and I shuffle this and later sort and my result is:

s1 s10 s11 s12 s13 s14 s15 s16 s2 s3 s4 s5 s6 s7 s8 s9 ss1

but I want to have

s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 ss1 

how to make this? Maybe special Comparator?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Larry
  • 101
  • 9
  • Why do you need this? If you want to sort by numerical order why are you using a `List` rather than a `List`? – Paul Boddington Mar 17 '16 at 21:01
  • 2
    @PaulBoddington I think he's trying to sort first by the alphabetical first part, and then by the numerical part as a number. Notice the `ss1` that he wants at the end. – childofsoong Mar 17 '16 at 21:01
  • @childofsoong Good point. I missed that. – Paul Boddington Mar 17 '16 at 21:01
  • 1
    I would recommend finding a tutorial on how to do a custom comparator. You need to figure out, based on your own input strings, how to split the string and integer parts (doesn't seem like it should be too hard), and then have your comparator compare accordingly. Alternatively, you could write a wrapper class for the items that stores a string and a number, implements `Comparable`, and has a `toString` that returns the strings as you have them up there. – childofsoong Mar 17 '16 at 21:03
  • I added my answer, look at – Andrew Tobilko Mar 17 '16 at 22:58

1 Answers1

1

You may use NaturalOrderComparator, this works fine:

Collections.sort(key, new NaturalOrderComparator());
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142