【问题标题】:Java program to sort a list of date which is in format dd MMM yyyy用于对格式为 dd MMM yyyy 的日期列表进行排序的 Java 程序
【发布时间】:2018-10-13 06:37:36
【问题描述】:

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

//映射到存储月份数据

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());

【问题讨论】:

标签: java sorting date


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    首先我会将日期字符串解析为日期对象

    DateFormat format = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
    Date date = format.parse("26 May 1960");
    

    您可以创建一个包含 Date 对象的对象,然后使其具有可比性。

    public class DateContainer implements Comparable<DateContainer > {
     private Date dateTime;
    
     public DateContainer (Date date){
      this.dateTime = date;
     }
    
     public Date getDateTime() {
      return dateTime;
     }
    
     public void setDateTime(Date datetime) {
      this.dateTime = datetime;
     }
    
     @Override
     public int compareTo(DateContainer o) {
       return getDateTime().compareTo(o.getDateTime());
     }
    }
    

    然后你可以创建一个上面的 Object 列表,然后使用 Collections 对其进行排序

    Collections.sort(myList);
    

    【讨论】:

    • 请不要教年轻人使用早已过时且臭名昭著的麻烦SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
    • 没错,有更好的实现。但是对于这个问题,当他们只是使用字符串时,任何解决方案都是更好的解决方案。
    【解决方案3】:
    public static void main(String[] args) {
        SimpleDateFormat f = new SimpleDateFormat("dd MMM yyyy");
        String[] input = {"20 Oct 2052",
                "26 May 1960",
                "06 Jun 1933",
                "06 Jun 1933",
                "06 Jun 1933",
        };
        Map<Long, String> result = new TreeMap<>();
        Stream.of(input)
                .filter(s -> s.length() == 11)
                .forEach(s -> {
                    try {
                        result.put(f.parse(s).getTime(), s);
                    } catch (ParseException e) {
                        System.out.println("Wrong Format: " + s);
                    }
                });
        System.out.println(result); // {-1154156400000=06 Jun 1933, -303033600000=26 May 1960, 2612970000000=20 Oct 2052}
    }
    

    使用 SimpleDateFormat 获取 Date 值并使用 TreeMap 来排序地图中的元素。

    希望对你有帮助!!!!

    【讨论】:

    • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
    【解决方案4】:

    这应该可以解决问题

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
    
    List<Date> dates = Arrays.stream(input).map(dateString -> {
    try {
        return simpleDateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
        return null;
    }).collect(Collectors.toList());
    dates.sort(Comparator.naturalOrder());
    
    dates.forEach(date -> System.out.println(simpleDateFormat.format(date)));
    

    这是一个两步过程

    1. 转换为 java.util.Date
    2. 排序日期列表并打印

    希望这会有所帮助!

    祝你好运!

    【讨论】:

    • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
    【解决方案5】:

    tl;博士

    这是一个使用现代 java.time 类和 lambda 语法的单线器。

    将每个字符串解析为LocalDate,收集、排序和重新生成字符串作为输出。

    Arrays.stream(
            new String[] { "20 Oct 2052" , "26 May 1960" , "06 Jun 1933" , "06 Jun 1933" , "06 Jun 1933" }
    )
            .map( input -> LocalDate.parse( input , DateTimeFormatter.ofPattern( "dd MMM uuuu" , Locale.US ) ) )
            .sorted()
            .map( date -> date.format( DateTimeFormatter.ofPattern( "dd MMM uuuu" , Locale.US ) ) )
            .collect( Collectors.toList() )
            .toString()
    

    [1933 年 6 月 6 日、1933 年 6 月 6 日、1933 年 6 月 6 日、1960 年 5 月 26 日、2052 年 10 月 20 日]

    步骤:

    • 生成数组元素的流(字符串输入)。
    • 处理每个输入,解析得到LocalDate
    • LocalDate对象进行排序
    • 在每个LocalDate 上,生成代表其值的文本。
    • 将每个生成的字符串收集到List
    • 生成表示字符串列表的文本,现在按时间顺序排序。

    智能对象,而不是哑字符串

    使用适当的数据类型,而不仅仅是字符串。

    对于没有时间和时区的仅日期值,请使用LocalDate 类。

    定义格式模式以匹配您的输入。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd MMM uuuu" , Locale.US );
    

    循环输入,将每个输入解析为LocalDate。将每个生成的LocalDate 收集到List 中。

        List < LocalDate > dates = new ArrayList <>( inputs.length );
        for ( String input : inputs ) {
            LocalDate ld = LocalDate.parse( input , f );
            dates.add( ld );
        }
    

    或者,改为使用简短而优美的 lambda 语法。

    List < LocalDate > dates = Arrays.stream( inputs ).map( input -> LocalDate.parse( input , f ) ).collect( Collectors.toList() );
    

    LocalDate 对象列表进行排序。

    Collections.sort( dates );
    

    以标准 ISO 8601 格式报告您的排序日期。

    String outputs = dates.toString() ;
    

    [1933-06-06、1933-06-06、1933-06-06、1960-05-26、2052-10-20]

    以任何所需格式报告您的排序日期。

       List < String > outputs = new ArrayList <>( dates.size() );
        for ( LocalDate date : dates ) {
            outputs.add( date.format( f ) );
        }
    

    [1933 年 6 月 6 日、1933 年 6 月 6 日、1933 年 6 月 6 日、1960 年 5 月 26 日、2052 年 10 月 20 日]


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

    从哪里获得 java.time 类?

    ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      相关资源
      最近更新 更多