Gpn008 Gpn008 - 1 month ago 9
Java Question

Sort arraylist by ignoring the - character in the beginnig if present

I want to sort an arraylist containing many lines

i want to ignore the ' - '

if it is the first letter of that line

INPUT

-bbb

a-aaa

-ddd

b-ddd

c-ccc

output

should be (as u can see it should be sorted on first character(a b c d )

a-aaa

-bbb

c-ccc

-ddd

e-eee

here is the code i have

Collections.sort(arrList, new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
if (o1.startsWith("-") && o2.startsWith("-")) {
return compare(o1.substring(1), o2.substring(1));
}

if (o1.startsWith("-")) {
return 1;
}
if (o2.startsWith("-")) {
return -1;
}

return o1.compareTo(o2);
}


});

Answer
final String o1s;
final String o2s;

if (o1.startsWith("|")) {
    o1s = o1.substring(1);
} else {
    o1s = o1;
}

if (o2.startsWith("|")) {
    o2s = o2.substring(1);
} else {
    o2s = o2;
}

return o1s.compareTo(o2s);

or, shorter but less readable

int o1offset = o1.startsWith("|") ? 1 : 0;
int o2offset = o2.startsWith("|") ? 1 : 0;

return o1.substring(o1offset).compareTo(o2.substring(o2offset));
Comments