按字母顺序对二维字符串数组进行排序 [英] 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();
}
}
输出应该是:
Albert TUR
Drake SOL
Eric CAN
Fred HAN
Victor ZSA
推荐答案
您可以创建实现接口的自定义比较器 Comparator
将 String[]
数组(数组 2D 行)作为参数并比较两个数组的第一个元素如下所示:
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]);
}
}
在你的 main
方法中执行排序后:
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();
}
}
这篇关于按字母顺序对二维字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!