对自定义类arraybuffer进行排序并在Scala中获取子集

时间:2019-03-12 09:21:26

标签: java scala sorting java-stream

我有一个自定义对象Employee的数组缓冲区,该缓冲区具有empname,empno,joiningdate

我想在连接日期时按desc顺序对ArrayBuffer进行排序,并获得前10名

这是我的工作方式,但我认为可以有更好的替代或优化解决方案

在数据库查询中无法执行相同操作,因为我使用的是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

1 个答案:

答案 0 :(得分:1)

如果您在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了解其他选项。