Scala program to concatenate two lists

1. Introduction

Concatenating two lists is a fundamental operation in programming. In Scala, you can combine lists using various methods, but the most intuitive is using the ++ operator. This blog post demonstrates how to concatenate two lists in Scala.

2. Program Steps

1. Initialize the Scala environment.

2. Create two separate lists.

3. Use the ++ operator to concatenate the two lists.

4. Print the concatenated list.

5. Execute the program.

3. Code Program

object ListConcatenator {
  def main(args: Array[String]): Unit = {
    // Define two sample lists
    val list1 = List(1, 2, 3)
    val list2 = List(4, 5, 6)

    // Concatenate the lists using the ++ operator
    val concatenatedList = list1 ++ list2

    println(s"List 1: $list1")
    println(s"List 2: $list2")
    println(s"Concatenated List: $concatenatedList")
  }
}

Output:

List 1: List(1, 2, 3)
List 2: List(4, 5, 6)
Concatenated List: List(1, 2, 3, 4, 5, 6)

Explanation:

1. The entire program is encapsulated within the ListConcatenator object.

2. We initialize two lists, list1 and list2, with different integer elements.

3. The ++ operator is used to concatenate the two lists, resulting in the concatenatedList.

4. We then print out the individual lists and the concatenated list to visualize the operation.

5. As shown in the output, the two lists List(1, 2, 3) and List(4, 5, 6) are combined to form the concatenatedList which is List(1, 2, 3, 4, 5, 6).


Comments