在
Seq 中获取实例的最佳实践是什么?
case class Point(x: Int, y: Int)
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
我想获取最大 y 的点数(在本例中为:Point(3, 30)
)
最好的方法是什么?
最简单的方法是使用TraversableOnce.maxBy
:
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
scala> points.maxBy(_.y)
res1: Point = Point(3,30)
@YuvalItzchakov的答案是正确的,但这里是另一种使用排序的方法:
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
// points: Seq[Point] = List(Point(1,10), Point(2,20), Point(3,30))
val order = Ordering.by((_: Point).y)
// order: scala.math.Ordering[Point] = scala.math.Ordering$$anon$9@5a2fa51f
val max_point = points.reduce(order.max)
// max_point: Point = Point(3,30)
或
points.max(order)
// Point = Point(3,30)
或带implicit
Ordering
:
{
implicit val pointOrdering = Ordering.by((_: Point).y)
points.max
}
// Point = Point(3,30)
注意:TraversableOnce.maxBy
也使用隐式排序。参考。
另一种方法是使用 foldleft。
val points:Seq[Point] = Seq(Point(1,10),Point(2,20),Point(3,30))
points.foldLeft[Point](Point(0,0)){(z,f) =>if (f.y>z.y) f else z}