Brandex07
Brandex07

Reputation: 85

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

I am trying to sort each row of a 2d String array in java.

Example:

For example, if an array contains:

ZCD
BFE
DZA

I want it to be sorted as:

CDZ
BEF
ADZ

Code:

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

Thanks. With the code above, its not sorting for some reason.

Upvotes: 1

Views: 174

Answers (2)

Saravana
Saravana

Reputation: 12817

You've almost done it, you can fix your code by debugging.

Here is an approach with java8 streams

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

output

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

Upvotes: 0

Amin J
Amin J

Reputation: 1209

Your sorting seems fine. The way you are printing is the issue.

Is this what you want?

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

Which produces this output:

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

Upvotes: 2

Related Questions