Scala program to find the intersection of two lists

1. Introduction

Finding the intersection of two lists is a common operation, where we determine the common elements between them. In Scala, there are intuitive and concise ways to accomplish this using standard library functions. In this blog post, we'll explore how to find the intersection of two lists in Scala.

2. Program Steps

1. Initialize the Scala environment.

2. Define two lists of numbers.

3. Use the intersect method to find common elements between the two lists.

4. Print the intersected list.

5. Execute the program.

3. Code Program

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

    // Find the intersection of the two lists using the intersect method
    val commonElements = list1 intersect list2

    println(s"List 1: $list1")
    println(s"List 2: $list2")
    println(s"Intersection: $commonElements")
  }
}

Output:

List 1: List(1, 2, 3, 4, 5)
List 2: List(4, 5, 6, 7, 8)
Intersection: List(4, 5)

Explanation:

1. Our Scala program is housed within the ListIntersection object.

2. We have two sample lists: list1 and list2.

3. The intersect method is applied on list1 using list2 as the argument. This method returns a new list containing all elements that are present in both lists.

4. We then print both sample lists and the intersection list to the console.

5. From the output, we see that the numbers 4 and 5 are common in both lists, thus they make up the intersection.


Comments