简体   繁体   中英

Sorting 2D array of strings in alphabetical order

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

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();
    }
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM