0

I have an ArrayList that contains strings like 2008-02-10T12:29:33.000

[2008-02-11T12:29:33.000, 2008-02-10T12:29:33.000]...

I want to sort this ArrayList in natural order. For this I have to convert this strings into a Date I quess. The order after sorting sorting the ArrayList above shoult be:

[2008-02-10T12:29:33.000, 2008-02-11T12:29:33.000]

The programming language that I use is Java.

pnuts
  • 58,317
  • 11
  • 87
  • 139
Nelly Junior
  • 556
  • 2
  • 10
  • 30
  • Agreed. It's just a matter of parsing and calling [Collections.sort(List)](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29) – wonderb0lt Jun 12 '15 at 14:08
  • 1
    I see that months are preceded by zero when needed. Does it also apply to rest of date elements like hours, minutes, seconds? If yes then as @gtgaxiola mentioned in [his answer](http://stackoverflow.com/a/30805122/1393766) you can simply sort it alphabetically (which is natural order for strings). – Pshemo Jun 12 '15 at 14:15

3 Answers3

4

Although you could just sort the strings, I would store those dates as LocalDateTimes instead of strings and keep them that way. That will make manipulating them much easier.

The transformation could look like:

List<String> list = Arrays.asList("2008-02-11T12:29:33.000", "2008-02-10T12:29:33.000");
List<LocalDateTime> dates = list.stream().map(LocalDateTime::parse).collect(toList());

(this works because your strings are in proper ISO format).

And then sorting is as simple as:

Collections.sort(dates);
assylias
  • 321,522
  • 82
  • 660
  • 783
2

I don't believe you need to do any conversion, as there is a natural order of those strings (at least I can't see a counterexample).

So Collections.sort() should do the trick.

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
  • Yes, you are right! I have not tried the sort as strings but it works. Ty! – Nelly Junior Jun 12 '15 at 14:29
  • 1
    @NellyJunior Notice that this will work only if used data formatting supports leading zeroes like `01:02:03.004`. Example: http://ideone.com/3vUuJu – Pshemo Jun 12 '15 at 14:36
  • @Pshemo good catch! This is exactly where the 'counterexample' could happen, but it seems is proper ISO 8601 format (so is always zero-padded) – gtgaxiola Jun 12 '15 at 14:41
0
ArrayList<String> dates = new ArrayList<String>();
dates.add("2008-02-11T12:29:33.000");
dates.add("2008-02-10T12:29:33.000");
Collections.sort(dates);
for (String date : dates)
{
  System.out.println(date);
}
Mrunmaya
  • 63
  • 8