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

问题描述 投票:1回答:5

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

//映射以存储月份数据

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
5个回答
2
投票

Radix Sort是你的朋友。只需使用此算法对字符串进这是最佳解决方案。


2
投票

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

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

然后,您可以创建上面的对象列表,然后使用集合对其进行排序

Collections.sort(myList);

1
投票
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获取到地图中已排序的元素。

希望能帮到你!!!!


1
投票

这应该可以解决问题

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. 对日期列表和打印进行排序

希望这可以帮助!

祝好运!


1
投票

tl;dr

这是一个使用现代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中。
  • 生成表示字符串列表的文本,现在按时间顺序排序。

Smart objects, not dumb strings

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

对于没有时间和没有时区的仅限日期的值,请使用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日]


About java.time

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

现在在Joda-Timemaintenance mode项目建议迁移到java.time班。

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

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

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如IntervalYearWeekYearQuartermore

© www.soinside.com 2019 - 2024. All rights reserved.