Reputation: 626
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
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
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