I'm trying to sort 'MMM YYYY' string according to date in Java (android).
For example:
Input:
---------
Sep 2019
Oct 2018
Nov 2019
Oct 2021
Nov 2011
Output:
---------
Nov 2011
Oct 2018
Sep 2019
Nov 2019
Oct 2021
I'm trying to sort 'MMM YYYY' string according to date in Java (android).
For example:
Input:
---------
Sep 2019
Oct 2018
Nov 2019
Oct 2021
Nov 2011
Output:
---------
Nov 2011
Oct 2018
Sep 2019
Nov 2019
Oct 2021
Create a Stream
of the given strings, parse each string of the Stream
into YearMonth
, sort the Stream
, map each YearMonth
element to the original format and finally, collect the Stream
into a collection.
Demo:
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM uuuu", Locale.ENGLISH);
List<String> sorted = Stream.of(
"Sep 2019",
"Oct 2018",
"Nov 2019",
"Oct 2021",
"Nov 2011"
)
.map(s -> YearMonth.parse(s, dtf))
.sorted()
.map(ym -> dtf.format(ym))
.collect(Collectors.toList());
// Display the list
sorted.forEach(System.out::println);
}
}
Output:
Nov 2011
Oct 2018
Sep 2019
Nov 2019
Oct 2021
Learn more about the modern Date-Time API* from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.
Your Question is not clear. I’ll assume your goal is to sort them by their chronological value.
YearMonth
classYearMonth
.YearMonth
objects into a NavigableSet
.