scala convert List(Some()) to List(string)

烂漫一生 提交于 2019-12-25 04:19:35

问题


how to convert a scala list of some types to list of strings Ex :

List(Some(1234), Some(2345), Some(45678))
to  List("1234","2345","45678")

回答1:


You can go for this:

scala> List(Some(1234), Some(2345), Some(45678)).flatten.map(x => x.toString)

res11: List[String] = List(1234, 2345, 45678)



回答2:


You can, as already suggested, flatten the collection and then map the toString method over its items, but you can achieve the same result in one pass by using collect:

val in = List(Some(1234), Some(2345), Some(45678))
val out = in.collect { case Some(x) => x.toString }

The collect method takes a partial function (defined with the case to destructure the Option) and applies it only to the items for which the partial function is defined (in this case, only Somes and not Nones).

You can read more about collect on the official documentation.

You can run an example and play with it here on Scastie.




回答3:


val str: List[String]= List(Some(123), 
Some(456), Some(789), None,
Some(234)).flatten.map(_.toString)
println(str) // will print List(123,456,789,234) 

Actually flatten will ignore all the None and take some which we are mapping to string.




回答4:


List(Some(1234), Some(2345), Some(45678)).flatten.map(_.toString)



回答5:


Map and match:

li.map {case Some (x) => Some (s"$x")}
res103: List[Some[String]] = List(Some(1234), Some(2345), Some(45678))


来源:https://stackoverflow.com/questions/49883636/scala-convert-listsome-to-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!