user3458716 user3458716 - 18 days ago 6
Scala Question

Add tuples containing (Integer,List.Empty) to existing List in scala

I am writing my first program in Scala. I am stuck at a point . I have a list lets call it listoriginal that contains values of the type (2,CompactBuffer(1, 3,5)) (1,CompactBuffer(3, 2)). Basically a (Integer, List) . I have an another list that contains a huge list of numbers. I am trying to iterate through this list and generate tuples of the (i,List.Empty). and this to the existing listoriginal to generate a finalList

val newList
for( i <- listofNumbers){
newList ++ (i,List.empty)
}
val finalList += originalList ++ newList

Answer

I think you are looking for the following code. You can use map() method of list to server your purpose.

val originalList = List((2,List(1, 3,5)),(1,List(3, 2)))
val numList = List(4, 2, 5, 7)

val newList = numList.map { x => (x, List.empty) }
val finalList = originalList++newList
println(finalList)