gpt4 book ai didi

Java 如何对二维字符串数组进行完全排序

转载 作者:行者123 更新时间:2023-12-01 11:29:45 25 4
gpt4 key购买 nike

大家好,我搜索了有关 java 中的二维数组排序的网站,它们都只涉及一列。我想知道如何在每一列中按字母顺序对二维数组进行排序。我尝试过使用比较器,但它只对一列进行排序。

我必须按每一列按字母顺序或反向字母顺序(取决于用户的选择)输出我的词库并输出一个表格。

String word[][] ={ 
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};

因此示例输出将是:

A/An "\t" ant "\t" a/an "\t" apple

Andrew "\t" ate "\t" juicy "\t" away

Alex "\t" ball "\t" jumped "\t" book

提前致谢!

最佳答案

您需要按列对数据重新排序,并对列进行排序。例如:

    String word[][] ={ 
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};
// generate the list of columns
List<List<String>> cols=new ArrayList<>();
for (String[] row:word){
for (int a=0;a<row.length;a++){
// create columns when needed
while(cols.size()<a+1){
cols.add(new ArrayList<String>());
}
List<String> col=cols.get(a);
col.add(row[a]);
}
}
// rewrite sorted words in word array
int colIdx=0;
for (List<String> col:cols){
// sort column
Collections.sort(col);
for (int a=0;a<col.size();a++){
word[a][colIdx]=col.get(a);
}
colIdx++;
}
// print
for (String[] row:word){
String sep="";
for (String w:row){
System.out.print(sep);
sep="\t";
System.out.print(w);
}
System.out.println();
}

关于Java 如何对二维字符串数组进行完全排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com