简体   繁体   English

将 Option[List[String]] 转换为 List[String]

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

How do we convert Option[List[String]] to List[String] in Scala?我们如何在 Scala 中将Option[List[String]]转换为List[String] I am trying to get a values from a Scala Map where key is a String and value is List[String] .我试图从 Scala Map中获取一个值,其中键是一个String ,值是List[String] But when I get the value for the key, it is being returned as Option[List[String]] .但是当我获得键的值时,它会作为Option[List[String]]

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如果您的代码在Try或其他异常处理程序中,或者您可以证明密钥在那里,那么这是替代方案

map(key)

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:可以通过调用toListOption转换为列表,然后您可以将其flatten以将列表列表转换为单个列表:

map.get(key).toList.flatten

This will return List[String] .这将返回List[String] If you try to retrieve a key that does not exist in the map it will return an empty list.如果您尝试检索地图中不存在的键,它将返回一个空列表。

You can also use getOrElse() method on map like:您还可以在地图上使用getOrElse()方法,例如:

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] . getOrElse()方法在映射中存在Key时返回实际 List[String] ,否则它将返回empty List[String]

One advantage of using getOrElse() method here is it makes your code more readable在这里使用getOrElse()方法的一个优点是它使您的代码更具可读性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM