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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With