-1

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
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • So you want to sort them by their chronological value? If so, say so. Your example data is not obvious. – Basil Bourque Oct 09 '21 at 18:15
  • Don’t keep your months as strings in your list. Just as you wouldn’t put numbers into an array of strings. Use proper data types. In this case keep a list of `YearMonth` objects. Sort them in natural order. If and when you need to give string output, format each `YearMonth` object into a string in your `MMM yyyy` format (or which format the receiver prefers). – Ole V.V. Oct 09 '21 at 18:57

2 Answers2

3

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

ONLINE DEMO

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Your Question is not clear. I’ll assume your goal is to sort them by their chronological value.

YearMonth class

  1. Parse each value as a YearMonth.
  2. Collect those YearMonth objects into a NavigableSet.
  3. Iterate that collection, generating your desired outputs.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154