tl;dr
This is a one-liner using modern java.time classes and lambda syntax.
Parse each string into a LocalDate
, collect, sort, and regenerate strings as output.
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]
Steps:
- Generate a stream of your array's elements (the string inputs).
- Process each input, parsing to get a
LocalDate
- Sort the
LocalDate
objects
- On each
LocalDate
, generate text representing its value.
- Collect each of those generated strings into a
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.
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
. Collect each resulting LocalDate
into a 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.
List < LocalDate > dates = Arrays.stream( inputs ).map( input -> LocalDate.parse( input , f ) ).collect( Collectors.toList() );
Sort the list of LocalDate
objects.
Collections.sort( dates );
Report your sorted dates in standard ISO 8601 format.
String outputs = dates.toString() ;
[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]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.