Search code examples
scalacase-classcalculation

Scala: Calculate Min, Max, Average with conditions


I have a case class defined like this:

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
                     )

Here are the data of the case class:

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

My question is how to calculate Min, Max, Average with a condition stock = IBM. Thanks for your support!

My problem has been solved thanks to @pme and @talex. Thank you all!


Solution

  • You have:

    val stockPrices: Seq[StockPrice]
    

    You can:

    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
    

    Check it out on scalafiddle