i have an array list of type String[]. i want to order it by String[0] as a int. i have this:
Collections.sort(listitems, new Comparator<String[]>() {
@Override
public int compare(String[] lhs, String[] rhs) {
return lhs[0].compareToIgnoreCase(rhs[0]);
}
});
but this order like this:
10
11
12
2
20
21
3
4
5
i have tried to convert the lhs[0] and rhs[0] to int, but the int type doesn't have any kind of compare and i'm not sure what type of int i need to return
The result from compare is meant to be:
So if you're sure that the first string of each array is parsable as an integer, I'd use:
@Override
public int compare(String[] lhs, String[] rhs) {
int leftInt = Integer.parseInt(lhs[0]);
int rightInt = Integer.parseInt(rhs[0]);
return leftInt < rightInt ? -1
: leftInt > rightInt ? 1
: 0;
}
Java 1.7 has the helpful Integer.compare method, but I assume that won't be available to you. You could use Integer.compareTo but that may create more garbage than you really want on a mobile device...
Note that this will work even when leftInt and rightInt are very large, or possibly negative - the solution of just subtracting one value from another assumes that the subtraction won't overflow.
I think this should do the work for you, if we assume that the contents of the arrays are string representations of integers:
Collections.sort(listitems, new Comparator<String[]>() {
@Override
public int compare(String[] lhs, String[] rhs) {
return Integer.valueOf(lhs[0]).compareTo(Integer.valueOf(rhs[0]));
}
});
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