简体   繁体   English

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

[英]Java program to sort a list of date which is in format dd MMM yyyy

Input is a list containing date in String format. 输入是一个包含字符串格式日期的列表。 I have solution as below. 我有如下解决方案。 But i feel it can be made more efficient. 但是我觉得可以提高效率。 Any help would be appreciated. 任何帮助,将不胜感激。

//Map to store month data //映射以存储月份数据

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

You can consider this as input 您可以将此视为输入

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


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

To compare result 比较结果

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

Sorting the result 结果排序

Collections.sort(temp1);

Printing the result 打印结果

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

Radix Sort is your friend. 基数排序是您的朋友。 Just sort strings with this algorithm. 只需使用此算法对字符串进行排序。 This is optimal solution. 这是最佳解决方案。

Firstly I would parse the date strings into a Date Object 首先,我将日期字符串解析为Date对象

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

You could create an object that holds a Date object then make it comparable. 您可以创建一个保存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());
 }
}

Then you could create a list of the Object above then use Collections to sort it 然后,您可以在上面创建对象的列表,然后使用“集合”对其进行排序

Collections.sort(myList);
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}
}

Use SimpleDateFormat to get Date value and TreeMap to sorted elements in the map. 使用SimpleDateFormat获取日期值,并使用TreeMap对地图中的已排序元素进行排序。

Hope that help you!!!! 希望对您有帮助!!!!

This should do the trick 这应该可以解决问题

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

this is a 2 step process 这是一个两步过程

  1. Convert to java.util.Date 转换为java.util.Date
  2. Sort the Date list and Print 排序日期列表并打印

Hope this helps! 希望这可以帮助!

Good luck! 祝好运!

tl;dr tl; dr

This is a one-liner using modern java.time classes and lambda syntax. 这是使用现代java.time类和lambda语法的单行代码

Parse each string into a LocalDate , collect, sort, and regenerate strings as output. 将每个字符串解析为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()

[06 Jun 1933, 06 Jun 1933, 06 Jun 1933, 26 May 1960, 20 Oct 2052] [1933年6月6日,1933年6月6日,1933年6月6日,1960年5月26日,2052年10月20日]

Steps: 脚步:

  • Generate a stream of your array's elements (the string inputs). 生成数组元素的流(字符串输入)。
  • Process each input, parsing to get a LocalDate 处理每个输入,进行解析以获取LocalDate
  • Sort the LocalDate objects 排序LocalDate对象
  • On each LocalDate , generate text representing its value. 在每个LocalDate ,生成表示其值的文本。
  • Collect each of those generated strings into a List . 将每个生成的字符串收集到List
  • Generate text representing the list of strings, now sorted in chronological order. 生成表示字符串列表的文本,现在按时间顺序排序。

Smart objects, not dumb strings 智能对象,而不是哑字符串

Use appropriate data types rather than mere strings. 使用适当的数据类型,而不仅仅是字符串。

For a date-only value without time-of-day and without time zone, use LocalDate class. 对于没有日期和时区的仅日期值,请使用LocalDate类。

Define a formatting pattern to match your inputs. 定义格式设置以匹配您的输入。

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

Loop the inputs, parsing each into a LocalDate . 循环输入,将每个输入解析为LocalDate Collect each resulting LocalDate into a List . 将每个结果LocalDate收集到一个List

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

Or instead, use the short and sweet lambda syntax. 或者,请使用简短的lambda语法。

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

Sort the list of LocalDate objects. LocalDate对象列表进行排序。

Collections.sort( dates );

Report your sorted dates in standard ISO 8601 format. 以标准ISO 8601格式报告您的排序日期。

String outputs = dates.toString() ;

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

Report your sorted dates in any desired format. 以任何所需的格式报告您的排序日期。

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

[06 Jun 1933, 06 Jun 1933, 06 Jun 1933, 26 May 1960, 20 Oct 2052] [1933年6月6日,1933年6月6日,1933年6月6日,1960年5月26日,2052年10月20日]


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM