Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String.split() result to Scala list

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
like image 547
WestCoastProjects Avatar asked Nov 19 '13 22:11

WestCoastProjects


People also ask

Does split turn a string into a list?

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.

How do I turn a string into a separated list?

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.

What does split return in Scala?

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.


1 Answers

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)
like image 177
dhg Avatar answered Oct 14 '22 09:10

dhg