遍历 case class 列表,只输出一个 case class
Iterate through a list of case class and just output a single case class
如何遍历案例列表 class 并只输出一个案例 class,只选择符合条件的行。
例如,对于案例class abc的列表,我想捕获满足特定条件的行。
case class abc(id: int, mod: Int, a: Int, b: Int)
case class output(id: int, mod: Int, calc: Int)
val a = List( abc(1, 101, 56, 47),
abc(1, 201, 34, 23))
val out1: Option[Output] = Some(output(1, 101, 103))
val b = List( abc(1, 101, 56, 47)
abc(1, 202, 47, 56))
val out2: Option[Output] = Some(output(1, 202, 103))
一般来说,你可以做你想做的事情:
list.foldLeft(None: Option[output]) {
case (Some(oldMax), a) =>
val newMax = ... // calculate output
Some(if (check if new output is bigger) newMax else oldMax)
case (None, a)
Some(calculate first max)
}
为了不破坏乐趣,我不会实现输出的比较和计算。
如何遍历案例列表 class 并只输出一个案例 class,只选择符合条件的行。
例如,对于案例class abc的列表,我想捕获满足特定条件的行。
case class abc(id: int, mod: Int, a: Int, b: Int)
case class output(id: int, mod: Int, calc: Int)
val a = List( abc(1, 101, 56, 47),
abc(1, 201, 34, 23))
val out1: Option[Output] = Some(output(1, 101, 103))
val b = List( abc(1, 101, 56, 47)
abc(1, 202, 47, 56))
val out2: Option[Output] = Some(output(1, 202, 103))
一般来说,你可以做你想做的事情:
list.foldLeft(None: Option[output]) {
case (Some(oldMax), a) =>
val newMax = ... // calculate output
Some(if (check if new output is bigger) newMax else oldMax)
case (None, a)
Some(calculate first max)
}
为了不破坏乐趣,我不会实现输出的比较和计算。