0

I have an arraybuffer of custom object Employee which has empname, empno, joiningdate

I wanted to sort ArrayBuffer on joiningdate with desc order and get top 10

This is how I did but I think there can be a better alternative or optimized solution for the same

Cannot do the same in db query since i am using cassandra db where I cannot do the same for non cluster columns

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
Naman
  • 27,789
  • 26
  • 218
  • 353
happy
  • 2,550
  • 17
  • 64
  • 109

1 Answers1

1

If you look in Scaladoc for methods with name including sort, you'll find sortBy. The only problem is how to use it to sort descending. You can either reverse the default Ordering:

val sorted = employeeList.sortBy(_.joiningdate)(Ordering[WhateverTheTypeOfJoiningDateIs].reverse)
sorted.take(10)

Or just sort ascending and take the last elements:

val sorted = employeeList.sortBy(_.joiningdate)    
sorted.takeRight(10).reverse

Use whichever you consider clearer.

Note sortBy doesn't sort in place (according to https://github.com/scala/collection-strawman/issues/25 Scala 2.13 was supposed to add methods for it, but I don't see them in https://www.scala-lang.org/files/archive/nightly/2.13.x/api/2.13.x/scala/math/Ordering.html). So doing toArray and sorting that in place will be faster.

There are also algorithms for top-N which don't require sorting the entire sequence, but they aren't available in the Scala or Java standard library, so far as I know. You can use Guava's Ordering or see Find top N elements in an Array for other options.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487