简体   繁体   中英

How can I prepend a string to list of elements in Scala?

I have the following requirement:

val lst = List("a","b","c")

I would like to prepend with the text test to all the elements in the list. The output should be like as below:

testa
testb
testc
val alteredList = lst.map(item => "test" + item)

Just to add some more options:

If you want a new List with the elements as you said:

val newList = lst.map("test".concat(_))

If you just want to print them, then you can do something like this:

lst.foreach(item => println(s"test$item"))

If you want to create list with such elements you could write: val result = list.map("test" + _)

After that of course you could print them all: result foreach println

In order to get that output you can write:

def main(args: Array[String]): Unit = {
  val lst = List("a","b","c")
  lst.map(s => "test" + s).foreach(println)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM