java - 基于一列对二维数组进行排序

标签 java arrays sorting

在 Java 中,我的数组中有如下数据

2009.07.25 20:24 Message A
2009.07.25 20:17 Message G
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 20:01 Message F
2009.07.25 21:08 Message E
2009.07.25 19:54 Message R

我想根据第一列对它进行排序,所以我的最终数据可以是这样的

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

第一列是格式“yyyy.MM.dd HH:mm”的日期,第二列是字符串。

最佳答案

Sort a two dimensional array based on one column
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.

既然你说二维数组,我假设“格式的日期......”是指一个字符串。下面是对 String[][] 的二维数组进行排序的代码:

import java.util.Arrays;
import java.util.Comparator;

public class Asdf {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } };

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

}

输出:

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

关于java - 基于一列对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4907683/

相关文章:

Javascript - For 循环无法正确找到数组中的值

Python:使用 lambda 键混淆进行排序

java - 比较器(排序)按优先级比较具有 3 个属性的对象数组列表

Java 投资返回率复合计算器

java - 解析查询: return a value from the done() method in the class?

php - foreach 不填充数组

Python 字符串和数组无法正常工作

java - 如何使用 Object 类型的参数调用 CriteriaBuilder.lessThan

java - 将偶数四舍五入为两位小数 "0"?

sorting - 使用 bindingsource 在正确位置向用户排序的 wingrid 添加新行