Come potrei ordinare un array 2d in Java? [duplicare]

Nov 19 2020

Quindi ho un array 2d in Java che è una stringa

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

Come dovrei ordinare le righe in ordine alfabetico?

Ho provato Arrays.sort(a), ma ha semplicemente restituito errori. E sento che sarà più complicato.

EDIT: l'output dovrebbe essere

Bob Smith Q 420 John Doe B 999 Nome qui T 123

Ho già il codice per stamparlo che funziona correttamente, devo solo ordinarlo alfabeticamente per righe.

Risposte

3 RohanKumar Nov 19 2020 at 07:38

Se vuoi solo ordinare le righe, penso che possa essere fatto in questo modo:

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

Questo dà il seguente output:

Bob Smith Q 420 
John Doe B 999 
Name Here T 123 
Laugslander Nov 19 2020 at 07:33

Puoi risolvere questo problema con gli stream:

String[] result = Arrays.stream(a)
        .map(inner -> String.join(" ", inner))
        .sorted()
        .toArray(String[]::new);
LuthermillaMuculadosReis Nov 19 2020 at 07:45

Prova questo

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