Mischa Mischa - 4 months ago 6
Java Question

How to sort an array of arrays by date?

In my android app I'm trying to get a sorted array. I've got an array of arrays with a name string and a date string. I'm trying to sort the names based on the dates. something like this:

private void sortList() {
String[][] namesAndDatesList = new String[][] {
new String[] {"name1", "05/03/2016 02:11:33")}
, new String[] {"name2", "04/03/2016 02:11:34"}
, new String[] {"name3", "04/03/2016 02:11:33")}
, new String[] {"name4", "02/03/2016 02:11:33")}
, new String[] {"name5", "05/03/2016 02:11:38")}
};

String[] namesList = Collections.sort(namesAndDatesList, new StringDateComparator());

}

class StringDateComparator implements Comparator<String>
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public int compare(params)
{
try {
// return something
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}


I would like it to output the names sorted by date and time like:

namesList = {name4, name3, name2, name1, name5}


I'm not sure how to do this.

Answer

You should parse the string into a date and then compare it, for android you can use Arrays.sort method and pass an anonymous comparator

Example:

private void sort2dArray() {
String[][] namesAndDatesList = new String[][] { new String[] { "name1", "05/03/2016 02:11:33" },
    new String[] { "name2", "04/03/2016 02:11:34" }, new String[] { "name3", "04/03/2016 02:11:33" },
    new String[] { "name4", "02/03/2016 02:11:33" }, new String[] { "name5", "05/03/2016 02:11:38" } };

Arrays.sort(namesAndDatesList, new Comparator<String[]>() {

    @Override
    public int compare(String[] o1, String[] o2) {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date d1 = null;
    Date d2 = null;
    try {
        d1 = sdf.parse(o1[1]);
        d2 = sdf.parse(o2[1]);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return d1.compareTo(d2);
    }
});
System.out.println(Arrays.deepToString(namesAndDatesList));
}
Comments