java order arraylist string [] by number
I have a list of arrays of type string [] I want to command it with string [0] as 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 is as follows: 10111222021345 I tried to convert LHS [0] and RHS [0] to int, but the int type has no type comparison. I don't know what type of int i need to return
Solution
The results of the comparison mean:
>Negative if the first parameter is logically "less than" the second parameter > positive if the first parameter is logically "more than" the second parameter > zero if the first parameter is logically equal to the second parameter
Therefore, if you are sure that the first string of each array can be resolved to an integer, I will 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 integer Compare method, but I don't think you can use it You can use integer CompareTo, but this may generate more garbage than the mobile device you really want
Note that this works even when leftint and rightint are very large, or may be negative - the solution of subtracting one value from another assumes that the subtraction does not overflow