如何在java中按字母顺序对二维数组进行排序

时间:2015-11-04 11:12:39

标签: java arrays sorting

假设我有一个二维数组:

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

我想根据第0列按字母顺序排序 所以adam首先是bob the jack - 而它(或新阵列)将如此:

{"adam","three"}
{"bob","one"},
{"jack","two"},

1 个答案:

答案 0 :(得分:2)

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

    }

}

<强>输出

亚当三 鲍勃一 杰克二世