简体   繁体   中英

How to alphabetically sort two dimensional array in java

Lets say i have a two dimensional array:

String [][] arr = {
{"bob","one"},
{"jack","two"},
{"adam","three"}
};

i would like to sort alphabetically according to column 0 so adam would be first the bob the jack - and it (or new array) will look like so:

{"adam","three"}
{"bob","one"},
{"jack","two"},
import java.util.Arrays;
import java.util.Comparator;


public class demo_sort {

    public static void main(String[] args) {

        final String[][] data = new String[][] {
                new String[] {"bob","one"},
                new String[] {"jack","two"},
                new String[] {"adam","three"}
                };

        Arrays.sort(data, new Comparator<String[]>() {
            @Override
            public int compare(final String[] entry1, final String[] entry2) {
                final String time1 = entry1[0];
                final String time2 = entry2[0];
                return time1.compareTo(time2);
            }
        });

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }

    }

}

output

adam three
bob one
jack two

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM