Home > front end >  how to sum only the max value for common prefix inside the array in scala
how to sum only the max value for common prefix inside the array in scala

Time:06-16

I have array contain string items in scala , each item contain from prefix || double value like below :

var y = Array("Zara||6.0", "Nuha||4.0","Zara||2.0","Zara||0.1")  

what I want to Do :

i need sum all double value from above array (y(i).split("\|\|")(1)) But if the prefix the duplicated in the array then I only want sum the max value like below : for item Zara we have 3 values i want to take the max (in our sample it 6.0) for item Nuha it unique then i will take it's value (4.0)

the excepted output is (6.0 4.0)=10.0

is there are any way to do it in scala rather than using 2 instead loop ?

CodePudding user response:

Prepare your array: extract prefix and values into tuple. Use foldLeft for aggregate max elem for each prefix, and sum values

val res = y.map(_.split("\\|\\|")).map(arr => (arr(0), arr(1).toDouble))
      .foldLeft(Map.empty[String, Double]) { (acc, elem) =>
        val value = acc.get(elem._1).map(math.max(_, elem._2)).getOrElse(elem._2)
        acc   (elem._1 -> value)
      }.values.sum
     
println(res)
  • Related