0

Please help, I'm having trouble how to sort Array of Strings in two columns. So, I have two columns: Both of it contains a string. I need to sort the first column in alphabetical order while the second column should not shuffle, thus, it should correspond to the first column after sorting.

Can anyone see where I need to put sorting method in my code below:

public static void main(String[] args) {
    String[][] emp = {
            {"Victor    ", "ZSA"},
            {"Fred    ", "HAN"},
            {"Drake   ", "SOL"},
            {"Albert  ", "TUR"},
            {"Eric    ", "CAN"}};

    System.out.println("String 1:    String 2: ");
    for (int i = 0; i < emp.length; i++) {
        for (int j = 0; j < emp[0].length; j++) {
            System.out.printf("%9s", emp[i][j]);
        }
        System.out.println();
    }
}

the output should be:

Albert  TUR
Drake   SOL
Eric    CAN
Fred    HAN
Victor  ZSA
0

2 Answers 2

1

You can create a custom comparator implementing the interface Comparator that takes the String[] arrays (array 2D rows) as argument and comparing the first elements of the two arrays like below:

public class CustomComparator implements Comparator<String[]> {
    @Override
    public int compare(String[] row1, String[] row2) {
        return row1[0].compareTo(row2[0]);
    }
}

After you can execute the sorting in your main method:

public static void main(String[] args) {
    String[][] emp = {
            {"Victor    ", "ZSA"},
            {"Fred    ", "HAN"},
            {"Drake   ", "SOL"},
            {"Albert  ", "TUR"},
            {"Eric    ", "CAN"}};

    Arrays.sort(emp, new CustomComparator());

    System.out.println("String 1:    String 2: ");
    for (int i = 0; i < emp.length; i++) {
        for (int j = 0; j < emp[0].length; j++) {
            System.out.printf("%9s", emp[i][j]);
        }
        System.out.println();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Arrays.sort(T[],Comparator) method as follows:

String[][] emp = {
        {"Victor ", "ZSA"},
        {"Fred   ", "HAN"},
        {"Drake  ", "SOL"},
        {"Albert ", "TUR"},
        {"Eric   ", "CAN"}};

// sort by first column alphabetically
Arrays.sort(emp, Comparator.comparing(arr -> arr[0]));

// output
Arrays.stream(emp).map(Arrays::toString).forEach(System.out::println);
[Albert , TUR]
[Drake  , SOL]
[Eric   , CAN]
[Fred   , HAN]
[Victor , ZSA]

See also:
How to sort by a field of class with its own comparator?
How to use a secondary alphabetical sort on a string list of names?

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.