Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list with string dates

Tags:

android

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.

like image 276
user1302569 Avatar asked Mar 17 '13 15:03

user1302569


2 Answers

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());
like image 172
Jules Avatar answered Nov 28 '22 08:11

Jules


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;
        }
     });
like image 39
Daniel Neu Avatar answered Nov 28 '22 10:11

Daniel Neu