S Jagdeesh
S Jagdeesh

Reputation: 1553

Sort MMM-yyyy in List without converting to Date

How could I sort the monthYear list without converting the string into Date object? I am not able to apply the logic here.

public class SortDates {

    public static void main(String[] args) {

        String[] monthName = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL",
                "AUG", "SEP", "OCT", "NOV", "DEC" };

        List<String> monthYear = new ArrayList<String>();

        monthYear.add("JAN-1999");
        monthYear.add("JUN-2009");
        monthYear.add("MAR-2003");
        monthYear.add("JAN-1998");
        monthYear.add("NOV-2013");

    }

}

Upvotes: 0

Views: 551

Answers (3)

Brian Agnew
Brian Agnew

Reputation: 272337

You can use Collections.sort(List<T> list,Comparator<? super T> c)

and specify your own comparator to parse those strings. See the doc for more details.

However, I would recommend converting to dates by parsing them using SimpleDateFormat, and strongly recommend actually storing them as dates, since that's what they really are. Currently your solution is stringly typed - I would prefer strongly typed since your compiler can work to verify what you're doing.

Upvotes: 2

Enrichman
Enrichman

Reputation: 11337

WHat about mapping the month with their numeric value?

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("JAN", 1);
...

and then check that?

Upvotes: 0

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31245

I would first describe the months in an enum:

enum Month{ JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

Then you can easily implement your own comparator:

public static class MyComparator implements Comparator<String>{
  @Override
  public int compare(String s1, String s2) {

    //If s1="JAN-1999", parts1[0]="JAN", parts1[1]="1999"
    String[] parts1=s1.split("-");
    //Month.valueOf("JAN") converts "JAN" to Month.JAN
    int m1 = Month.valueOf(parts1[0]).ordinal();
    int year1 = Integer.valueOf(parts1[1]);

    String[] parts2=s2.split("-");
    int m2 = Month.valueOf(parts2[0]).ordinal();
    int year2 = Integer.valueOf(parts2[1]);

    return ...//Here, compare year1 to year2 and if necessary, m1 and m2
    //You can also return (100*year2+m2) - (100*year1+m1)
  }
}

Then use it to sort :

Collections.sort(monthYear, new MyComparator());

Upvotes: 3

Related Questions