0

I have a two dimensional array filled with strings in Java. I want to be able to sort the entire array relative to the column I have chosen to sort by.

For Example:

Say I have an Array of data that looks like this.

|John  | C | Doe    |

|Sally | A | Miller |

|Chris | B | Sanders|

I specify that I want to sort in descending order based on their middle initial and am returned an array that looks like this.

|John  | C | Doe    |

|Chris | B | Sanders|

|Sally | A | Miller |

Is there a way to designate a Comparator that will do this?

2 Answers 2

1

Sure, just pass the column index in as a parameter of the comparator.

class ColumnComparator<T extends Comparable<T>> implements Comparator<T[]> {
  private final int column;

  ColumnComparator(int column) { this.column = column; }

  @Override public int compare(T[] a, T[] b) {
    return a[column].compareTo(b[column]);
  }
}

or, more simply, if it is always column 1 and string arrays:

class ColumnComparator implements Comparator<String[]> {
  @Override public int compare(T[] a, T[] b) {
    return a[1].compareTo(b[1]);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Another quick question. Would this still work in a Java 6 implementation?
I don't see why it wouldn't. Generics came in Java 5; Comparator and Comparable were both in Java 1.2.
Thank you for the quick and informative response :)
0

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        String[][] array = {{"John", "C", "Doe"}, {"Sally", "A", "Miller"}, {"Chris", "B", "Sanders"}};
        Arrays.sort(array, new IndexComparator(0));
        for(int i = 0; i < array.length; i++) {
            System.out.println(array[i][0]);
        }
    }
}

class IndexComparator implements Comparator {
    private int index = 0;

    public IndexComparator(int index) {
        this.index = index;
    }


    @Override
    public int compare(String[] o1, String[] o2) {
        return o1[index].compareTo(o2[index]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.