Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best efficient way to sort Months and Year in Java

Tags:

java

datetime

I have a list which contains dates in format (MON-YYYY) in string format, I need to sort this list.The approach I have followed till now is reading the list and converting the string in date format and using compare option, but i am not getting the desired result

Code Snippet

List<String> abc = new ArrayList<String>();
        List<Date> xyz = new ArrayList<Date>();

        abc.add("JAN-2010");
        abc.add("JAN-2011");
        abc.add("APR-2013");
        abc.add("NOV-2009");

        try {

            for (String abc1 : abc) {

                Date date;

                date = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH)
                        .parse(abc1);
                xyz.add(date);

            }

            Collections.sort(xyz, new Comparator<Date>() {

                public int compare(Date arg0, Date arg1) {
                    // return arg0.getDate().compareTo(o2.getDate());
                    return arg0.compareTo(arg1);
                }
            });

            for (Date date1 : xyz) {
                System.out.println("Sorted : " + date1);
            }

        } catch (ParseException e) {

            e.printStackTrace();

        }
    }

Output

    Sorted : Sun Nov 01 00:00:00 IST 2009
Sorted : Fri Jan 01 00:00:00 IST 2010
Sorted : Sat Jan 01 00:00:00 IST 2011
Sorted : Mon Apr 01 00:00:00 IST 2013

Expected Output

NOV-2009
JAN-2010
JAN-2011
APR-2013

I am also not sure if the above code is perfect in performance perspective as converting the string and parsing would take a long time if I have thousands of dates in MON-YYYY format in the list.

like image 708
S Jagdeesh Avatar asked Mar 23 '23 10:03

S Jagdeesh


1 Answers

Ok, I see you corrected the typo.

Now, remember you need to use a DateFormatter also when you present the data, in addition to when you parse it.

So please try this:

        for (Date date1 : xyz) {
            System.out.println("Sorted : " + new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH).format(date1));
        }

You might want to make the SimpleDateFormat available to all methods of your class as a field.

Additional info: please be aware SimpleDateFormat is known to not be thread-safe. You can use ThreadLocal as one solution to that.

Good luck.

like image 172
vikingsteve Avatar answered Mar 26 '23 00:03

vikingsteve