使用现代 Java
Answer by Andreas 是正确的。这是一个变体,它使用了添加到更高版本 Java 中的新功能。
使用List.of 制作一些示例数据。结果列表是不可修改的。因此,将不可修改的列表提供给ArrayList 的构造函数,以获得我们可以排序的可修改列表。
List < String > strings = new ArrayList <>(
List.of(
"2015-08-27T22:24:31.903" ,
"2018-08-27T22:24:31.903" ,
"2016-08-27T22:24:31.903" ,
"2017-08-27T22:24:31.903"
)
);
按文本排序
如其他答案中所述,您的字符串采用标准 ISO 8601 格式。该特定格式设计为按字母顺序排序时按时间顺序排列。因此,如果此任务是您获取此数据的唯一目标,则无需将其解析为日期时间对象。只需按文本排序,如String 对象。
List 接口没有使用Collections 实用程序类,而是获得了sort 方法。该方法需要Comparator。我们可以调用Comparator.naturalOrder() 来生成实例,而不是实现该接口。
strings.sort( Comparator.naturalOrder() );
转储到控制台。
System.out.println( "strings = " + strings );
看到这个code run live at IdeOne.com。
字符串 = [2015-08-27T22:24:31.903, 2016-08-27T22:24:31.903, 2017-08-27T22:24:31.903, 2018-08-27T22:24:31.903]
按日期时间对象排序
如果您将进一步使用此输入,则将其解析为日期时间对象。
现代方法使用 java.time 类。
我们可以简化示例数据,因为我们可以直接使用由List.of 生成的不可修改的List。
List < String > strings =
List.of(
"2015-08-27T22:24:31.903" ,
"2018-08-27T22:24:31.903" ,
"2016-08-27T22:24:31.903" ,
"2017-08-27T22:24:31.903"
);
将LocalDateTime 对象中的List 设为空。
List < LocalDateTime > ldts = new ArrayList <>( strings.size() );
通过一次解析一个输入字符串来填充该列表,生成一个LocalDateTime 对象。将该对象添加到我们的列表中。
请注意,java.time 类默认使用 ISO 8601 格式。所以不需要指定格式模式。
for ( String string : strings )
{
ldts.add( LocalDateTime.parse( string ) ); // Parsing text in ISO 8601 format needs no formatting pattern to be specified.
}
排序,就像我们在上面所做的那样。致电List::sort,传递Comparator。
ldts.sort( Comparator.naturalOrder() ) ;
看到code run live at IdeOne.com。
System.out.println( "ldts = " + ldts );
流
如果我们想要花哨的话,我们可以用Stream 替换for 循环。我们可以单线完成这项工作。
List < String > strings =
List.of(
"2015-08-27T22:24:31.903" ,
"2018-08-27T22:24:31.903" ,
"2016-08-27T22:24:31.903" ,
"2017-08-27T22:24:31.903"
);
List < LocalDateTime > ldts =
strings
.stream()
.map( s -> LocalDateTime.parse( s ) )
.sorted()
.collect( Collectors.toList() )
;
System.out.println( "ldts = " + ldts );
ldts = [2015-08-27T22:24:31.903, 2016-08-27T22:24:31.903, 2017-08-27T22:24:31.903, 2018-08-27T22:24:31.903]