list.filter(_.bar.isDefined) match {
case Nil => Foo(None)
case l => l.minBy(_.bar)
}
Or, if there will always be at least one non-empty option, then simply list.filter(_.bar.isDefined).minBy(_.bar)
This is (slightly) better than sorting because it is linear and does not require data structure isolation.
Another possibility that is even (a little) more effective (but a little more),
list.reduceOption {
case (Foo(None), x) => x
case (x, Foo(None)) => x
case (Foo(Some(x)), Foo(Some(y))) => if ( x < y ) Foo(Some(x)) else Foo(Some(y))
}
source
share