Home > OS >  Merging lists in scala
Merging lists in scala

Time:03-16

I have to merge these two lists together in a way that results in the 3rd list. I'm not super familiar with Scala that much but I am always interested in learning.

val variable = List("a", "b", "c") | val number = List("1", "2", "3")

When merged and printing each value after, it should result in an output like this

a is equal to 1 b is equal to 2 c is equal to 3

with a list that is now equal to

List("a is equal to 1", "b is equal to 2", "c is equal to 3")

Please help me out

CodePudding user response:

zip and map would work,

variable.zip(number).map {case (str, int) => s"$str is equal to $int"}

CodePudding user response:

Alternativly, you could use for-comprehensions

Welcome to Scala 3.1.1 (17, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                                          
scala> val variable = List("a", "b", "c")
val variable: List[String] = List(a, b, c)
                                                                                                          
scala> val number = List("1", "2", "3")
val number: List[String] = List(1, 2, 3)
                                                                                                          
scala> for {
     |   str <- variable
     |   n <- number
     | } yield s"$str is equal to $n"
val res0: List[String] = List(a is equal to 1, a is equal to 2, a is equal to 3, b is equal to 1, b is equal to 2, b is equal to 3, c is equal to 1, c is equal to 2, c is equal to 3)
  • Related