2016-09-17 5 views
1

Javaで2d String配列の各行をソートしようとしています。Arrays.sortを使用してJavaの2d String配列の各行をソートする方法は?

例えば、配列が含まれている場合:

CDZ 
BEF 
ADZ 

コード

private String[] commonCollections; 

private int comparisons = 0; 

public Comparable[] findCommonElements(Comparable[][] collections){ 

    for(int i = 0; i < collections.length; i++){ 
     Arrays.sort(collections[i]); 
    } 

    for(int i = 0; i <collections[0].length; i++){ 
     System.out.print(collections[0][i] + "\n"); 
    } 

    return commonCollections; 
} 

ZCD 
BFE 
DZA 

が、私はそれは次のように並べ替えることにしたいです

ありがとうございました。上記のコードでは、何らかの理由でソートされません。

+0

ストリーム?空の配列を返すことを指している場合は、空の配列を返すためです。 commonCollectionは初期化しません。あなたが意味することを明確にしてください。 –

+0

あなたはどのように要素を格納していますか?私たちは仮定して答えることができます。 – YoungHobbit

答えて

2

あなたの並べ替えはうまくいくようです。あなたが印刷する方法が問題です。

これは必要なものですか?この出力を生成

public class Main { 


    public static Comparable[][] findCommonElements(Comparable[][] collections){ 


     for(int i = 0; i < collections.length; i++){ 
      Arrays.sort(collections[i]); 

     } 

     return collections; 
    } 

    public static void main(String[] args) { 

    Character [][]input= {{'Z','C','D'},{'B','F','E'},{'D','Z','A' }}; 

    Comparable[][] output = findCommonElements(input); 

    for(int i = 0; i <output.length; i++){ 
     System.out.print(Arrays.toString(output[i]) + "\n"); 
    }  
    } 
} 

[C、D、Z] [B、E、F] [A、D、Z]

+0

ちょっといいキャッチ! –

0

あなたはほとんどそれを、あなたがすることができますやりましたデバッグしてコードを修正してください。ここで

はjava8とアプローチであり、出力を何

char[][] arr = { { 'Z', 'C', 'D' }, { 'B', 'F', 'E' }, { 'D', 'Z', 'A' } }; 
    char[][] sorted = IntStream.range(0, arr.length).mapToObj(i -> arr[i]).peek(x -> Arrays.sort(x)).toArray(char[][]::new); 
    for (char[] js : sorted) 
     System.out.println(Arrays.toString(js)); 

出力

[C, D, Z] 
[B, E, F] 
[A, D, Z] 
関連する問題