Home > Software design >  SCALA- get higher percentage of a value filtering keys
SCALA- get higher percentage of a value filtering keys

Time:11-22

here is my question: I have a map with keys like regions and values a seq of characteristics of persons of this regions:

("Asia" -> [Person(region: "Asia", hair: "brown", eyes: "blue",....), Person(.......)
("America" -> [Person(region: "America", hair: "red", eyes: "brown",....), Person(.......)

i have to return which region has the higher percentage of blue eyed persons but i dont know how to access to the characteristics of each person. i can acces values like grouped.count(_._2 == "blue"). can someone help me? thanks in advance

CodePudding user response:

You have to decompose your problem in multiple steps:

  • compute the percentage of blue eyes for each region
  • find the max

Which can actually be solved with a single method maxBy in Scala:

val population: Map[String, Seq[Person]] = ???

val (region, persons) = population
  .maxBy { case (region, persons) =>
    persons.count(_.eyes == "blue") / persons.size
  }

Consider using maxByOption to be safer in case your map is empty

See https://www.scala-lang.org/api/current/scala/collection/Map.html#maxBy[B](f:A=>B)(implicitcmp:scala.math.Ordering[B]):A

  • Related