Java order arraylist string [] by number
I have a list of arrays of type String []. I want to order it by String [0] as int. I have it:
Collections.sort(listitems, new Comparator<String[]>() {
@Override
public int compare(String[] lhs, String[] rhs) {
return lhs[0].compareToIgnoreCase(rhs[0]);
}
});
but this order looks like this:
10
11
12 page 2 20
21 page 3 of 4 page 5 I tried to convert lhs[0]
and rhs[0]
to int
but the type int
has no comparison and I'm not sure which type int
I need to return
source to share
The result compare
should be:
- Negative if the first argument is logically "less" than the second
- Positive if the first argument is logically greater than the second
- Zero if the first argument is logically equal to the second
So, if you are sure that the first line of each array will be parsed as an integer, I would 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 a useful method Integer.compare
, but I assume it won't be available to you. You can use it Integer.compareTo
, but it can create more junk than you really want on a mobile device ...
Note that this will work even when leftInt
u rightInt
are very large or possibly negative, the solution to simply subtracting one value from another assumes that the subtraction will not overflow.
source to share
I think this should do the job for you, assuming 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]));
}
});
source to share