scalamaxscala-optionlistbuffer

Get max in a ListBuffer of Some[Long] in Scala


This piece of code works fine and returns 343423 as expected:

val longList: ListBuffer[Long] = ListBuffer(103948,343423,209754)
val maxLong = longList.max

But it doesn't work for Some[Long]:

val longSomeList: ListBuffer[Some[Long]] = ListBuffer(Some(103948),Some(343423),Some(209754))
val maxSomeLong = longSomeList.max

Error: No implicit Ordering defined for Some[Long].
val maxSomeLong = longSomeList.max

Is there any simple solution to get the max of the second list?

max function from TraversableForwarder(scala.collection.generic)


Solution

  • You are looking for .flatten.

     longSomeList.flatten.max
    

    Or give it the ordering to use explicitly:

     longSomeList
       .max(Ordering.by[Option[Int], Int](_.getOrElse(Int.MinValue)))
    

    Also, don't use mutable collections.