1

I have the following list in input and :

val list=List("aimee,Paris,10",
"alex,Nice,12",
"Sara,Paris,15")

and I want to have a multiline String as output with the following format:

val output:String="aimee Paris,
alex Nice,
Sara Paris")

I wrote the following code

def listToMultLine (input:List[String]):String ={
input.map(_.split(",")).map(x => List(x(0),x(1)).mkString(","))
}

but this gives me erronous output thanks a lot for your help

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
scalacode
  • 1,096
  • 1
  • 16
  • 38
  • Possible duplicate of [Scala: join an iterable of strings](https://stackoverflow.com/questions/13529512/scala-join-an-iterable-of-strings) – Andrey Tyukin Jun 08 '18 at 10:52

4 Answers4

2

.mkString is the solution for you which would concat all the elements in a collection to a String.

But looking at your output suggests that you want to remove the last digit and want each element in next line of the string.

So following should get you your desired output

scala> list.map(x => x.substring(0, x.lastIndexOf(","))).mkString(", \n")
res0: String =
aimee,Paris,
alex,Nice,
Sara,Paris
Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
0

You can use the very mighty foldLeft(), check out this blog to know more

 scala> list.map{
     | word => word.split(",").take(2)
     | }.foldLeft("")((complete, current)=>complete + current(0)+ ","+ current(1)+",\n")

You will get the desired output.

0

It seems you want to omit the last digit, so I would to suggest to use this solution, which is more readable than Ramesh's similar solution thanks to pattern-matching:

list.map(s => {
  val Seq(name,city,age) = s.split(',')
  (name,city)
}).mkString(", \n")

or alternatively

list.map(s => s.split(','))
  .map{case Seq(name,city,age) => (name,city)}
  .mkString(", \n")

res0: String = (aimee,Paris), 
(alex,Nice), 
(Sara,Paris)
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145
0

Try This:

list.map(_.split(",")).map{case Array(a,b,c)=>a+" "+b}.mkString(",\n")

In SCALA REPL:

scala> val list=List("aimee,Paris,10", "alex,Nice,12", "Sara,Paris,15")
list: List[String] = List(aimee,Paris,10, alex,Nice,12, Sara,Paris,15)

scala> list.map(_.split(",")).map{case Array(a,b,c)=>a+" "+b}.mkString(",\n")
res62: String =
aimee Paris,
alex Nice,
Sara Paris

scala>
RAGHHURAAMM
  • 1,099
  • 7
  • 15