2015-05-28 36 views
0

嗨,大家好我在網站上搜索了關於二維數組排序的網站,他們都只涉及一列。我想知道如何在每列中按字母順序排列二維數組。我試過使用比較器,但它只排序一列。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"}, 
    }; 

所以例如輸出將是:

一/一個 「\ t」 的螞蟻 「\ t」 的一/一個 「\ t」 的蘋果

安德魯 「\ t」 的吃「\ t」 的水靈 「\ t」 的遠

亞歷克斯 「\ t」 的球 「\ t」 的提前躍升 「\ t」 的書

謝謝!

+0

最好提供一些你已經嘗試過的代碼。 –

+0

創建對應於每列的集合,然後對它們進行排序。例如,您的第一個列表將包含「The」,「It」,「A/an」等。您將爲每個「列」都有一個集合。它應該是直接的,你如何填充每個集合。 – swingMan

回答

1

您需要按列重新排序數據,並對列進行排序。例如:

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