您可以使用foldLeft
來計算一個解析的總和。如flatMap
然後sum
方法採取列表的兩個分析。
val sum = notes.foldLeft(0)({ case (acc, note) => acc + note.note.getOrElse(0) })
還...你是如何定義你的情況AVG,
// lets say you have this list of notes
val notes = ListBuffer(Note("[email protected]", Some(2)), Note("[email protected]", Some(3)), Note("test.gmail.com", None))
// Now what is supposed to be your avg
// Do you want to consider a None as 0 or do you want to ignore it
// is it -> (3 + 2 + 0)/3 = 5/3
// or is it -> (3 + 2)/2 = 5/2
// If you want to consider a None as 0 then,
val (sum, count) = notes.foldLeft((0, 0))({
case ((acc, count), note) => {
note.note.map(i => (i + acc, count + 1)).getOrElse((acc, count + 1))
}
})
val avg = sum/count
// if you want to ignore all None then,
val (sum, count) = notes.foldLeft((0, 0))({
case ((acc, count), note) => {
note.note.map(i => (i + acc, count + 1)).getOrElse((acc, count))
}
})
val avg = sum/count
注意與此解決方案,以避免'java.lang.ArithmeticException:/由zero'時'numbers.length == 0「,即沒有音符時。 – Eric
@Eric不錯的提示! –