Skip to content
Advertisement

How to sort a list of months with years

I have a list of months with years such as: [12-2014,11-2012,5-2014,8-2012] and I have to sort them with the most recent on top (or the latest date on top) eg. [12-2014,5-2014,11-2012,8-2012] .
Does anybody have any idea on how to do this in Java efficiently?

EDIT:
The class YearMonth is not available, I’m on Java 7

Advertisement

Answer

Since you are using Java 7 you can take advantage of the Date class as well as the Comparator interface and its usage in a Set object like the treeSet for instance.

Here is an implementation of the Comparator interface to compare two dates

public class MonthYearComparator implements Comparator<Date> {

    public int compare(Date o1, Date o2) {
        // TODO Auto-generated method stub
        return -1*o1.compareTo(o2);
    }

}

And then here is how we could use it. First I will use a SimpleDateFormat class to parse your strings as dates. To do that I need to complete them and make them look as formated date strings. Since the day is irrelevant for the comparison I could take any day like “01”.

Once I have turned them into Date objects I will add them to a instance of a TreeSet which is provided with a Comparator and they will automatically be sorted as I add them.

Then I can substract the part of the date that I need which will be a substring(3) of my date object after being formated as a string.

Here is the code (for demo sake I used the same datas that you provided as example):

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class MonthYearIssue {

    private List<String> listOfMonthYears = new ArrayList<String>();
    private static final String USED_DATE_FORMAT = "dd-MM-yyyy";
    SimpleDateFormat formatter = new SimpleDateFormat(USED_DATE_FORMAT);

    public void setUpMonthYearsList() {
        listOfMonthYears.add("12-2014");
        listOfMonthYears.add("11-2012");
        listOfMonthYears.add("5-2014");
        listOfMonthYears.add("8-2012");
    }

    public Date parseToDate(String monthYearString) throws ParseException {
        return formatter.parse("01-" + monthYearString);
    }

    public List<String> doSort() throws ParseException {

        List<String> result = new ArrayList<String>();
        Set<Date> dates = new TreeSet<Date>(new MonthYearComparator());

        for (String monthYearStr: listOfMonthYears) {
            dates.add(parseToDate(monthYearStr));

        }

        for (Object d: dates.toArray()) {

            result.add(formatter.format((Date)d).substring(3));
        }

        System.out.println(result);
        return result;

    }

    public static void main(String[] args) throws ParseException {
        MonthYearIssue issueSolver = new MonthYearIssue();
        issueSolver.setUpMonthYearsList();
        issueSolver.doSort();
    }

}

Here is the result:

[12-2014, 05-2014, 11-2012, 08-2012]

Advertisement