簡體   English   中英

如何使用Arrays.sort對Java 2d字符串數組中的每一行進行排序?

[英]How to sort each row in a 2d String array in java using Arrays.sort?

我正在嘗試在Java中對2D字符串數組的每一行進行排序。

范例

例如,如果數組包含:

ZCD
BFE
DZA

我希望將其排序為:

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

謝謝。 使用上面的代碼,由於某種原因其無法排序。

您的排序似乎很好。 問題是您的打印方式。

這是你想要的嗎?

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]

您已經差不多完成了,可以通過調試來修復代碼。

這是使用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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM