Scala:根据条件计算最小值,最大值,平均值

时间:2018-11-29 08:52:42

标签: scala case-class calculation

我有一个如下定义的案例类:

def case_class(): Unit = {
   case class StockPrice(quarter : Byte,
                      stock : String,
                      date : String,
                      open : Double,
                      high : Double,
                      low : Double,
                      close : Double,
                      volume : Double,
                      percent_change_price : Double,
                      percent_change_volume_over_last_wk : Double,
                      previous_weeks_volume : Double,
                      next_weeks_open : Double,
                      next_weeks_close : Double,
                      percent_change_next_weeks_price : Double,
                      days_to_next_dividend : Double,
                      percent_return_next_dividend : Double
                     )

以下是案例类别的数据:

1,IBM,3/4/2011,162.36,164.31,159.41,161.83,21549118,-0.326435,0.491083418,21443811,161.60,162.43,0.513614,63,0.463449
1,IBM,3/11/2011,161.60,167.72,158.85,162.43,31119857,0.513614,44.41359967,21549118,161.16,155.89,-3.27004,56,0.461737
1,IBM,3/18/2011,161.16,161.98,151.71,155.89,41827781,-3.27004,34.40865426,31119857,157.64,162.18,2.87998,49,0.481108
1,IBM,3/25/2011,157.64,162.74,157.07,162.18,25381792,2.87998,-39.31833965,41827781,161.54,164.27,1.68998,42,0.462449
1,INTC,1/7/2011,21.01,21.21,20.27,20.66,386719626,-1.66587,0,0,20.71,21.08,1.78658,27,0.871249
1,INTC,1/14/2011,20.71,21.33,20.57,21.08,274111012,1.78658,-29.11892917,386719626,21.03,20.82,-0.998573,20,0.85389
1,INTC,1/21/2011,21.03,21.20,20.62,20.82,218479469,-0.998573,-20.29526016,274111012,21.03,21.46,2.0447,13,0.864553

我的问题是如何在条件stock = IBM下计算最小值,最大值,平均值。感谢您的支持!

@pme @talex 解决了我的问题。谢谢大家!

2 个答案:

答案 0 :(得分:0)

假设您有对象列表:

list: Seq[StockPrice]

并希望拥有最小和最大open

val min = list.map(x=>x.open).min
val max = list.map(x=>x.open).max

获得平均水平

val sum = list.map(x=>x.open).sum
val count = list.size
val avg = sum / count

要过滤它,您可以按照以下步骤

val filteredList = list.filter(p => p.stock == 'IBM')

答案 1 :(得分:0)

您有:

val stockPrices: Seq[StockPrice]

您可以:

val filtered = stockPrices
                 .filter(_.stock == "IBM") // filter for IBM
                 .map(_.open) // map to the price

val average = filtered.sum / filtered.length
val min = filtered.min
val max = filtered.max

scalafiddle上查看