What is the means to convert the following java String[] to a Scala List?
val trimmedList : List[String] = str.split("\\n")).map (_.trim) // Missing some code here, does not compile
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
You can also convert a string to a list using a separator with the split() method. The separator can be any character you specify. The string will separate based on the separator you provide. For example, you can use a comma, , , as the separator.
The split method returns an array of String elements, which you can then treat as a normal Scala Array : scala> "hello world".split(" ").foreach(println) hello world.
For simplicity, use toList
:
val trimmedList: List[String] = str.split("\\n").map(_.trim).toList
For complexity, use breakOut
(which avoids creating an intermediate collection from map
):
import collection.breakOut
val trimmedList: List[String] = str.split("\\n").map(_.trim)(breakOut)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With