w3resource

Scala Programming: Merge (concatenate) given Lists

Scala Programming List Exercise-12 with Solution

Write a Scala program to merge (concatenate) given lists.

Sample Solution:

Scala Code:

object Scala_List
{
  def main(args: Array[String]): Unit = 
 {
   val nums1 = List(1,3,5,7,9)
   val nums2 = List(2,4,6,8,10)
   println("Original Lists:")
   println(nums1)
   println(nums2)
   println("Merge the said two lists using the ++ method:")
   val nums_1 = nums1 ++ nums2
   println(nums_1)
   println("Using ::: way:")
   val nums_2 = nums1 ::: nums2
   println(nums_2)
   println("Using concat method:")
   val nums_3 = List.concat(nums1, nums2)
   println(nums_3)
  }
}

Sample Output:

Original Lists:
List(1, 3, 5, 7, 9)
List(2, 4, 6, 8, 10)
Merge the said two lists using the ++ method:
List(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Using ::: way:
List(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Using concat method:
List(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the index of an element in a given list.
Next: Write a Scala program to find the even and odd numbers from a given list.

What is the difficulty level of this exercise?