I have this list of Strings
Car1
Car2
Car3
......
Carn
I want to sort this list according to numerics in it.
for instance if I have Car3, Car1, Car12, Car45
,
I want it to be sorted like Car1, Car3, Car12, Car45
.
I have used Collections.sort()
, but it returns something like Car1, car12, car3, Car45
.
what should I do to put it in correct order?
You need a custom Comparator, something like
Collections.sort(list, new Comparator<String>() {
public int compare(String s1, String s2) {
int i1 = Integer.parseInt(s1.replaceAll("\\D", ""));
int i2 = Integer.parseInt(s2.replaceAll("\\D", ""));
return Integer.compare(i1, i2);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With