问题
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 Some
s and not None
s).
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