1

So I have a 2d array In Java that is a String

String a[][] = new String[3][4];
a[0][0] = "John";
a[0][1] = "Doe";
a[0][2] = "B";
a[0][3] = "999";
a[1][0] = "Bob";
a[1][1] = "Smith";
a[1][2] = "Q";
a[1][3] = "420";
a[2][0] = "Name";
a[2][1] = "Here";
a[2][2] = "T";
a[2][3] = "123";

How would I go about sorting the rows alphabetically?

I tried Arrays.sort(a), but it just threw back errors. And I feel like its gonna be more complicated that.

The output should be:

Bob Smith Q 420
John Doe B 999
Name Here T 123

I already have the code for printing it working properly, just need to sort it alphabetically by rows.

Community
  • 1
  • 1

3 Answers3

3

If you only want to sort the rows, I think it can be done like this:

Arrays.sort(a, (o1, o2) -> {
    String firstO1Element = o1[0];
    String firstO2Element = o2[0];
    return firstO1Element.compareTo(firstO2Element);
});

This gives the following output:

Bob Smith Q 420 
John Doe B 999 
Name Here T 123 
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
0

You can solve this problem with streams:

String[] result = Arrays.stream(a)
        .map(inner -> String.join(" ", inner))
        .sorted()
        .toArray(String[]::new);
Laugslander
  • 386
  • 2
  • 16
0

Try this:

Arrays.sort(a, (b, c) -> b[0] - c[0]);
Community
  • 1
  • 1
Luthermilla Ecole
  • 666
  • 1
  • 6
  • 14