gopi
gopi

Reputation: 33

convert Option[List[String]] to List[String]

How do we convert Option[List[String]] to List[String] in Scala? I am trying to get a values from a Scala Map where key is a String and value is List[String]. But when I get the value for the key, it is being returned as Option[List[String]].

Upvotes: 1

Views: 816

Answers (3)

Tim
Tim

Reputation: 27421

The best solution is

map.getOrElse(key, Nil)

If your code is inside a Try or other exception handler, or if you can prove that the key is there, then this is the alternative

map(key)

Upvotes: 4

Tausif Sayyad
Tausif Sayyad

Reputation: 258

You can also use getOrElse() method on map like:

map.get(key).getOrElse(List.empty[String])

getOrElse() method return actual List[String] when Key is present in map otherwise it will return the empty List[String].

One advantage of using getOrElse() method here is it makes your code more readable

Upvotes: -1

gutch
gutch

Reputation: 7139

Option can be turned into a list by calling toList, which you can then flatten to turn the list-of-lists into a single list:

map.get(key).toList.flatten

This will return List[String]. If you try to retrieve a key that does not exist in the map it will return an empty list.

Upvotes: 3

Related Questions