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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With