我有一个自定义对象Employee的arraybuffer,它有empname,empno,joineddate
我想在加入日期时使用desc顺序对ArrayBuffer进行排序并获得前10名
这就是我的方式,但我认为可以有更好的替代方案或优化的解决方案
不能在db查询中执行相同的操作,因为我使用cassandra db,其中我不能对非群集列执行相同操作
val employeeList: mutable.Buffer[Employee]// getting from db
val employeeMap = employeeList.groupBy((p: Employee) => p.joiningdate)
val employeeDescSortedMap = new mutable.TreeMap[java.util.Date,
mutable.Buffer[Employee]]()(Ordering.ordered[java.util.Date].reverse)
val limitedSizeEmployeeMap = new mutable.TreeMap[java.util.Date, mutable.Buffer[Employee]]()
var count: Long = 10
employeeDescSortedMap ++= employeeMap
employeeDescSortedMap.foreach(employee => {
if (count > 0) {
limitedSizeEmployeeMap += employee
count -= 1
}
})
limitedSizeEmployeeMap
如果你在Scaladoc中查找名称包括sort
的方法,你会发现sortBy
。唯一的问题是如何使用它来降序排序。您可以撤消默认的Ordering
:
val sorted = employeeList.sortBy(_.joiningdate)(Ordering[WhateverTheTypeOfJoiningDateIs].reverse)
sorted.take(10)
或者只是升序排序并采用最后的元素:
val sorted = employeeList.sortBy(_.joiningdate)
sorted.takeRight(10).reverse
使用您认为更清楚的。
注意sortBy
没有排序到位(根据https://github.com/scala/collection-strawman/issues/25 Scala 2.13应该为它添加方法,但我没有在https://www.scala-lang.org/files/archive/nightly/2.13.x/api/2.13.x/scala/math/Ordering.html中看到它们)。所以做toArray
和排序将更快。
还有top-N的算法,它们不需要对整个序列进行排序,但据我所知,它们在Scala或Java标准库中不可用。您可以使用Guava's Ordering
或其他选项来查看Find top N elements in an Array。