[英]Java How do I sort a 2D string array entirely
嗨,大家好,我搜索了有關Java中2D數組排序的網站,它們都只涉及一列。 我想知道如何在每一列中按字母順序對2D數組排序。 我試過使用比較器,但它只對一列進行排序。
我必須按每一列以字母或反向字母(取決於用戶的選擇)輸出我的詞庫,並輸出一個表格。
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 /一個“ \\ t”螞蟻“ \\ t”一個/一個“ \\ t”蘋果
安德魯“ \\ t”吃了“ \\ t”多汁的“ \\ t”
亞歷克斯“ \\ t”球“ \\ t”跳了“ \\ t”書
提前致謝!
您需要按列對數據重新排序,然后對列進行排序。 例如:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.