Scala program to remove duplicates from a list

1. Introduction

Removing duplicates from a list is a frequently encountered task in data processing. Given a list like List(1, 2, 2, 3, 3, 3, 4), after removing duplicates, it should become List(1, 2, 3, 4). In this post, we will exhibit a Scala program that eliminates duplicates from a provided list.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the list that contains duplicates.

4. Implement a function to remove the duplicates.

5. Call the function and display the resultant list without duplicates.

6. Execute the program.

3. Code Program

object RemoveDuplicatesApp {
  def main(args: Array[String]): Unit = {
    // Define the list with duplicates
    val originalList = List(1, 2, 2, 3, 3, 3, 4)

    println(s"Original list: $originalList")

    // Remove duplicates and print the resulting list using the removeDuplicates function
    val noDuplicatesList = removeDuplicates(originalList)
    println(s"\nList after removing duplicates: $noDuplicatesList")
  }

  // Function to remove duplicates from a list
  def removeDuplicates[A](lst: List[A]): List[A] = {
    lst.distinct
  }
}

Output:

Original list: List(1, 2, 2, 3, 3, 3, 4)
List after removing duplicates: List(1, 2, 3, 4)

Explanation:

1. We start with an object named RemoveDuplicatesApp. In Scala, the main method, serving as the program's entry point, is nested within an object.

2. Within the main function, we have a value originalList, symbolizing the list with duplicate elements.

3. We then present the originalList to the user.

4. The function removeDuplicates takes care of eliminating duplicates from a given list. For this purpose, it utilizes the built-in distinct method which returns a new list excluding any duplicate elements.

5. The main function calls the removeDuplicates method, obtains the list devoid of duplicates, and showcases the result.

6. The output initially reveals the originalList and then introduces the list after the removal of duplicate elements.


Comments