KosWarm
KosWarm

Reputation: 626

Scala map get several values if contains in map

How to get several values from the Map if they exist? For this I use the following code

val params:mutable.Map[String,String]=mutable.Map.empty
Seq(params.lift("Name"),params.lift("Surname")).flatten.mkString(" ")

But maybe there is a better solution?

Upvotes: 1

Views: 273

Answers (2)

stefanobaghino
stefanobaghino

Reputation: 12814

As suggested in a comment, a for comprehension can get the job done as well. Depending on personal taste, either approach can be preferred:

import scala.collection.mutable

def multiget[K, V](map: scala.collection.Map[K, V], keys: K*): Seq[V] =
  for {
    key <- keys
    value <- map.get(key)
  } yield value

val data = mutable.Map("Name" -> "John", "Surname" -> "Smith")
multiget(data, "Name", "Surname").mkString(" ")

Upvotes: 2

Ruslan Batdalov
Ruslan Batdalov

Reputation: 793

I am not sure that it is what you want, but I think this modification of your second line is a little more readable:

Seq("Name", "Surname").flatMap(params.lift(_)).mkString(" ")

Upvotes: 6

Related Questions