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.

5
  • 3
    Does this answer your question? sorting 2D array of String in java Commented Nov 19, 2020 at 7:11
  • No, that looks like it sorts based on the number rather than the first letter in the first column. Thanks for the suggestion though! Commented Nov 19, 2020 at 7:32
  • 1
    You only want to sort the rows? What's the expected output? Commented Nov 19, 2020 at 7:32
  • 1
    The expected output is [[Bob Smith Q 420][John Doe Q 420][Name Here T 123]], I already have the printing command set up. Commented Nov 19, 2020 at 7:35
  • ohk, Please see if my answer helps. I tested it it seems to be printing the same output Commented Nov 19, 2020 at 7:39

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

You can solve this problem with streams:

String[] result = Arrays.stream(a)
        .map(inner -> String.join(" ", inner))
        .sorted()
        .toArray(String[]::new);

Comments

0

Try this:

Arrays.sort(a, (b, c) -> b[0] - c[0]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.