Sorting array of strings that contain number

Caio Ambrosio :

I'm implementing some code for my college and I have to sort two classes by its name. So, I started using Java's compareTo for Strings, but it wasn't doing it correctly. For example, I have these two names TEST-6 and TEST-10. But, the result was TEST-10 ahead of TEST-6.

I've searched and got this solution:

private int compare(String o1, String o2) {
    return extractInt(o1) - extractInt(o2);
}
private int extractInt(String s) {
    String num = s.replaceAll("\\D", "");
    // return 0 if no digits found
    return num.isEmpty() ? 0 : Integer.parseInt(num);
}

But my strings could assume any form. And when I tried this test: TEST-6 and TEST10) the result was TEST-6 ahead of TEST10, but what I expect is TEST10 then TEST-6.

The expected result should be normal string comparison, but comparing the full number when it is needed. So if substrings before numbers are equal, the number is compared, if not, keep string comparison. Or something like this:

TE
TES-100
TEST-1
TEST-6
TESTT-0
TEXT-2
109
Mushif Ali Nawaz :

You can do something like that:

list.sort(Comparator.comparing(YourClass::removeNumbers).thenComparing(YourClass::keepNumbers));

These are two methods:

private static String removeNumbers(String s) {
    return s.replaceAll("\\d", "");
}

private static Integer keepNumbers(String s) {
    String number = s.replaceAll("\\D", "");
    if (!number.isEmpty()) {
        return Integer.parseInt(number);
    }
    return 0;
}

For following data:

List<String> list = new ArrayList<>();
list.add("TEXT-2");
list.add("TEST-6");
list.add("TEST-1");
list.add("109");
list.add("TE");
list.add("TESTT-0");
list.add("TES-100");

This is the sorting result:

[109, TE, TES-100, TEST-1, TEST-6, TESTT-0, TEXT-2]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328491&siteId=1