Reputation: 99
I have two lists
val list1 = List("customer1", "customer2")
list1: List[String] = List(customer1, customer2)
val list2 = List("John||32||Phone","Michael||34||Laptop")
list2: List[String] = List(John||32||Phone, Michael||34||Laptop)
I'm trying to get output as below list
List((customer1,John),(customer1,32),(customer1,Phone),(customer2,Michael),(customer2,34),(customer2,Laptop))
Below is my code
val finalList = list1 zip list2
finalList: List[(String, String)] = List((customer1,John||32||Phone), (customer2,Michael||34||Laptop))
finalList.foreach{
case (fieldName,fieldDetail) => {
val cusList = fieldName + "-" + fieldDetail.replace("||",",")
val cusDetailList = cusList.split("-") match {
case Array(k, v) =>
v.split(",").map(value => (k, value)).toList
}
println(cusDetailList)
}
}
It prints as
List((customer1,John), (customer1,32), (customer1,Phone))
List((customer2,Michael), (customer2,34), (customer2,Laptop))
I'm unable to get the output list as below
List((customer1,John),(customer1,32),(customer1,Phone),(customer2,Michael),(customer2,34),(customer2,Laptop))
Upvotes: 0
Views: 55
Reputation: 78
You need to flatten the result list. This does the trick:
val list = list1 zip list2 flatMap {
case (s1, s2) => s2.split("\\|\\|").map((s1, _))
}
Upvotes: 2
Reputation: 142263
Try using flatten
:
scala> val lol = List(List(1,2), List(3,4))
lol: List[List[Int]] = List(List(1, 2), List(3, 4))
scala> val result = lol.flatten
result: List[Int] = List(1, 2, 3, 4)
Or flatMap
.
Upvotes: 1