对TimeStamp的scala arrayBuffer进行排序

ase*_*ims 2 timestamp scala

我有这个功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

我试图对阵列进行排序但不能.我收到此错误:

No implicit Ordering defined for java.sql.Timestamp.
Run Code Online (Sandbox Code Playgroud)

我知道我需要定义如何完成排序.有没有办法像Java一样轻松地对它进行排序:Collections.sort(list); 或者使用Scala有更好的方法?

om-*_*nom 18

或者,在课堂的某个地方定义它,你很高兴:

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
Run Code Online (Sandbox Code Playgroud)


Seb*_*oek 5

mList.sortWith(_.compareTo(_) < 1)
Run Code Online (Sandbox Code Playgroud)

注意,使用匿名函数,您可以传递一个显式函数,如下所示:

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

mList.sortWith(comparator)
Run Code Online (Sandbox Code Playgroud)

Timestamp本身没有隐式排序,这里我们只是使用该compareTo方法进行排序.

感谢@Nick指出排序getTime()并不是在所有情况下都是不够的.我还查看了before您期望工作的方法,但这仅使用了epoch值进行比较.