[请帮助,我在如何将字符串数组分为两列时遇到麻烦。因此,我有两列:两者都包含一个字符串。我需要按字母顺序对第一列进行排序,而第二列不应乱序排列,因此,它应与排序后的第一列相对应。
谁能在下面的代码中看到我需要在何处放置排序方法:
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();
}
输出应为:阿尔伯特·图尔德雷克SOL埃里克·坎韩维克多ZSA
您可以创建一个以Comparator数组为参数并比较两个数组的第一个元素的String[]
,如下所示:
public class CustomComparator implements Comparator<String[]> {
@Override
public int compare(String[] row1, String[] row2) {
return row1[0].compareTo(row2[0]);
}
}
您可以在main
方法中执行排序后:
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();
}
}