Reputation: 1459
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")
Upvotes: 0
Views: 1721
Reputation: 2686
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.
Upvotes: 2
Reputation: 12814
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.
Upvotes: 2
Reputation: 36269
Map and match:
li.map {case Some (x) => Some (s"$x")}
res103: List[Some[String]] = List(Some(1234), Some(2345), Some(45678))
Upvotes: 1
Reputation: 1190
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)
Upvotes: 4