1
List<String[]> data = Importer.readCsv("test.csv");

A String[] item looks like this:

  1. Position: name (String)
  2. Position: 2017-03-14 18:22:44.149 (String)

What is a good approach in order to sort the list by the timestamp descending? I search for a solution without creating new Objects.

lidox
  • 1,901
  • 3
  • 21
  • 40

3 Answers3

4

Use Collection.sort() and Comparator.comparing(), I find those easy to read when coming back to it later:

data.sort(Comparator.comparing((String[] o) -> o[1]).reversed());

You can compare the timestamp without conversion, as the format is "correctly" ordering the fields.


If you are confined to Java 7, there will be more boilerplate:

Collections.sort(data, new Comparator<String[]>()
{
    @Override
    public int compare(String[] o1, String[] o2)
    {
        return o2[1].compareTo(o1[1]);
        // return -o1[1].compareTo(o2[1]);
    }
});

Note that I need to compare o2 to o1 in this order or negate the result of comparing o1 to o2 to order the data descending. This becomes much more obvious in the first approach.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
1

You could use a custom Comparator that takes the second element in each array and converts it to a Timestamp. Note that a Comparator's function can't throw an exception, so you'd have to catch the potential ParseException and deal with it:

Function<String[], Date> parser = s -> {
    try {
        return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(s[1]);
    } catch (ParseException e) {
        return null;
    }
};

list.sort(Comparator.comparing(parser));
shmosel
  • 49,289
  • 6
  • 73
  • 138
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Well, thank you very much for your suggestions and impulses. Special Thanks goes to XtremeBaumer! Following code does the job too:

List<String[]> data = importer.readCsv(context, csvFile);


Collections.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] item1, String[] item2) {

        String dateString1 = item1[1];
        String dateString2 = item2[1];

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        Date date1 = null;
        Date date2 = null;

        try {
            date1 = format.parse(dateString1);
            date2 = format.parse(dateString2);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

        // dateString1 is an earlier date than dateString2
        return date1.compareTo(date2);
    }
});
lidox
  • 1,901
  • 3
  • 21
  • 40