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.
You've parsed your dateString
to actual Date
object. And java.util.Date
can't be formatted. Only a String
representation of that Date
object can be got.
You need to change your comparator to compare your dateString
format by internally converting the Strings to date.
If you are gonna sort the Date
objects, you'll get the output you've got. Also, as mentioned by @darijan , change your logic in the comparator.
First i think it's better to have only one instance of SimpleDateFormat
and always use this to parse your dates.
I also suggest to create this instance of SimpleDateFormat
in front of your try
block, so you solve your second problem and can use SimpleDateFormat.format(date)
to parse your dates back to requested stringformat.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.