Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to sum only the max value for common prefix inside the array in scala

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading