I have a small problem. I have a ArrayList listOfSData where every element is some like a date: for example:
[30-03-2012, 28-03-2013, 31-03-2012, 2-04-2012, ...]
Now I was wondering how can I sort this list. I mean I want to sort to this
[28-03-2013, 30-03-2012, 31-03-2012, 2-04-2012, etc].
This list must have String values. How can I sort this list? Help me because I have no idea how can I do that.
You will need to implement a Comparator<String>
object that translates your strings to dates before comparing them. A SimpleDateFormat
object can be used to perform the conversion.
Something like:
class StringDateComparator implements Comparator<String>
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
public int compare(String lhs, String rhs)
{
return dateFormat.parse(lhs).compareTo(dateFormat.parse(rhs));
}
}
Collections.sort(arrayList, new StringDateComparator());
here is a small example based on your input. This could be done with a few lines less, but I thought this would be better to understand. Hope it helps.
List<String> values = new ArrayList<String>();
values.add("30-03-2012");
values.add("28-03-2013");
values.add("31-03-2012");
Collections.sort(values, new Comparator<String>() {
@Override
public int compare(String arg0, String arg1) {
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy");
int compareResult = 0;
try {
Date arg0Date = format.parse(arg0);
Date arg1Date = format.parse(arg1);
compareResult = arg0Date.compareTo(arg1Date);
} catch (ParseException e) {
e.printStackTrace();
compareResult = arg0.compareTo(arg1);
}
return compareResult;
}
});
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