Assuming you reconsider to using list of tuples instead of sequence of maps
val tuples = List(
("k1", 1),
("k1", 2),
("k2", 3),
("k2", 4)
)
try foldLeft
like so
tuples.foldLeft(Map.empty[String, Int]) { case (acc, t @ (key, value)) =>
acc.get(key) match {
case Some(oldValue) => if (oldValue >= value) acc else acc + t
case None => acc + t
}
}
// val res0: Map[String,Int] = Map(k1 -> 2, k2 -> 4)
or using updatedWith
tuples.foldLeft(Map.empty[String, Int]) { case (acc, t @ (key, value)) =>
acc.updatedWith(key) {
case Some(oldValue) => Some(math.max(oldValue, value))
case None => Some(value)
}
}
// val res1: Map[String,Int] = Map(k1 -> 2, k2 -> 4)
This should be rather performant because we are single-passing thorough the list and Map
's lookup/add has by default effectively constant time.