Sorting 2D array of strings in alphabetical order

穿精又带淫゛_ 提交于 2021-01-28 09:14:01

问题


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

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



回答2:


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?



来源:https://stackoverflow.com/questions/61912105/sorting-2d-array-of-strings-in-alphabetical-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!