Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list of Strings having integer values- Java [duplicate]

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?

like image 795
Just_another_developer Avatar asked Dec 01 '22 21:12

Just_another_developer


1 Answers

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);
        }
    });
like image 129
Evgeniy Dorofeev Avatar answered Dec 04 '22 11:12

Evgeniy Dorofeev