Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort scala arrayBuffer of TimeStamp

I have this function:

def getTime() : ArrayBuffer[Timestamp] = {
    val offset = Timestamp.valueOf("2015-01-01 00:00:00").getTime()
    val end = Timestamp.valueOf("2015-01-02 00:00:00").getTime()
    val diff = end - offset + 1

    val mList = ArrayBuffer[Timestamp]()

    val numRecords = 3
    var i = 0
    while (i < numRecords) {
      val rand = new Timestamp(offset + (Math.random() * diff).toLong)

      mList += rand
      i += 1
    }

  //  mList.toList.sortWith(_ < _); 
   // scala.util.Sorting.quickSort(mList.toArray);
}

I have tried to sort the array but could not. I get this error:

No implicit Ordering defined for java.sql.Timestamp.

I know I need to define how the ordering would be done. Is there a way to sort it easily as in Java: Collections.sort(list); or there is a better approach using Scala?

like image 903
aselims Avatar asked May 01 '15 11:05

aselims


2 Answers

Alternatively, define it somewhere in your class and you're good to go:

implicit def ordered: Ordering[Timestamp] = new Ordering[Timestamp] {
    def compare(x: Timestamp, y: Timestamp): Int = x compareTo y
}
getTime().sorted // now this will work just fine
like image 79
om-nom-nom Avatar answered Sep 18 '22 16:09

om-nom-nom


mList.sortWith(_.compareTo(_) < 1)

Note that's with an anonymous function, you could pass an explicit function, which would look like this:

def comparator(first: Timestamp, second: Timestamp) = first.compareTo(second) < 1

mList.sortWith(comparator)

There's no implicit ordering on Timestamp itself, here we're just sorting using the compareTo method.

Thanks to @Nick for pointing out sorting on getTime() wasn't suffient in all scenarios. I also looked at the before method which you would expect to work, but this only compares using the epoch value as well.

like image 24
Sebastiaan van den Broek Avatar answered Sep 19 '22 16:09

Sebastiaan van den Broek