user1005633
user1005633

Reputation: 755

Sort multiple type multidimension array by specific column

I have a multidimension String array. It contains numbers and strings. Is there any way to sort it by a specific integer column? e.g. I have this:

  1. Fox | 32 | One
  2. Dog | 45 | Two
  3. Cat | 34 | Three
  4. Snake | 3 | Four

I want to sort this String array by integer column. For example:

  1. Dog | 45 | Two
  2. Cat | 34 | Three
  3. Fox | 32 | One
  4. Snake | 3 | Four

I tried with this but it requires integer array.

Arrays.sort(temp, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
    return Integer.compare(o2[1], o1[1]);
}});

Upvotes: 0

Views: 65

Answers (1)

user and
user and

Reputation: 560

This solve your issue: (updated)

public static void main(String[] args) {
    String[][] temp = {
        { "Fox", "32", "One" },
        { "Dog", "45", "Two" },
        { "Cat", "34", "Three" },
        { "Snake", "3", "Four" }
    };

    Arrays.sort(temp, new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return Integer.compare(
                    Integer.parseInt(row1[1]), Integer.parseInt(row2[1]));
        }
    });

    System.out.println(Arrays.deepToString(temp));
}

Upvotes: 1

Related Questions