keerthi
keerthi

Reputation: 23

Scala - Create a new list by by concatenating elements from list 1 list 2 elements in functional style

I have two lists, "firstName" and "lastName", I want to create a new list "fullName" by concatenating corresponding elements (Strings) from first list and second list as show below.

Input Lists:

firstName: List[String] = List("Rama","Dev")
lastName: List[String] = List("krish","pandi")

Expected output:

Fullname:List[String] = List("Rama krish", "Dev Pandi")

Could you please let me know how this can be achieved in functional style?

Upvotes: 1

Views: 70

Answers (1)

Travis Brown
Travis Brown

Reputation: 139028

Taking this step by step, the first thing to do is to zip the lists to get a new list of pairs:

scala> val firstName: List[String] = List("Rama","Dev")
firstName: List[String] = List(Rama, Dev)

scala> val lastName: List[String] = List("krish","pandi")
lastName: List[String] = List(krish, pandi)

scala> firstName.zip(lastName)
res0: List[(String, String)] = List((Rama,krish), (Dev,pandi))

Note that if the lists aren't the same length, the longer one will be truncated.

Next you can use map to take each pair and turn it into a new string:

scala> firstName.zip(lastName).map {
     |   case (first, last) => s"$first $last"
     | }
res1: List[String] = List(Rama krish, Dev pandi)

I'm using string interpolation here (the s"$variableName" part), but you could also just use + to concatenate the strings.

Upvotes: 3

Related Questions