用于对格式为 dd MMM yyyy 的日期列表进行排序的 Java 程序

标签 java sorting date

输入是一个包含字符串格式的日期的列表。我有如下解决方案。但我觉得它可以变得更有效率。任何帮助将不胜感激。

//映射存放月份数据

HashMap<String,String> month = new HashMap<String,String>();
        month.put("Jan","01");
        month.put("Feb","02");
        month.put("Mar","03");
        month.put("Apr","04");
        month.put("May","05");
        month.put("Jun","06");
        month.put("Jul","07");
        month.put("Aug","08");
        month.put("Sep","09");
        month.put("Oct","10");
        month.put("Nov","11");
        month.put("Dec","12");

你可以将其视为输入

    String[] input = {"20 Oct 2052",
    "26 May 1960",
    "06 Jun 1933",
    "06 Jun 1933",
    "06 Jun 1933",
};


    ArrayList<Long> temp1 = new ArrayList<Long>();

比较结果

    HashMap<Long,String> temp2 = new HashMap<Long,String>();

    ArrayList<String> result = new ArrayList<String>();
    for(int i = 0 ; i< input.length ; i++){
        String j = "";
        if(input[i].length() == 11){

            j+= input[i].substring(7,11);
            j+= month.get(input[i].substring(3,6));
            j+=input[i].substring(0,2);

            temp1.add(Long.parseLong(j));
            temp2.put(Long.parseLong(j), input[i]);   
        }
    }

排序结果

Collections.sort(temp1);

打印结果

System.out.println(temp1.toString());

最佳答案

Radix Sort是你的 friend 。只需使用此算法对字符串进行排序。这是最优解。

关于用于对格式为 dd MMM yyyy 的日期列表进行排序的 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774434/

相关文章:

java - 如何在 JUnit 和 Java 中使用 stub ?

java - 带有韩语的 Android TTS

java - 事务性保存而不调用更新方法

c++ - 如何 list.sort(member Function);?

php - 根据另一个表中的关联字符串查询和排序以分号分隔的 id 列表的最有效方法是什么?

sql - 时间戳和系统日期

hibernate - JPA 使用 ZoneOffset 存储 OffsetDateTime

java - 何时将 QueryRequest 与适用于 AWS 的 Java SDK 一起使用?

c++ - 对表格进行排序 C++

r - 在 R 中去掉日期和时间,这样你就有了每个数字组件