Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java order arraylist string[] by number

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

like image 878
Joaolvcm Avatar asked May 15 '26 20:05

Joaolvcm


2 Answers

The result from compare is meant to be:

  • Negative if the first argument is logically "less than" the second
  • Positive if the first argument is logically "more than" the second
  • Zero if the first argument is logically equal to the second

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.

like image 166
Jon Skeet Avatar answered May 17 '26 08:05

Jon Skeet


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]));
 }
});
like image 34
Boris Strandjev Avatar answered May 17 '26 09:05

Boris Strandjev