Scala program to remove duplicates from list

Scala program | Remove duplicates from a list: Here, we are going to learn how to remove duplicates from a given list using different methods?
Submitted by Shivang Yadav, on July 03, 2020 [Last updated : March 11, 2023]

Scala Lists

List in Scala is a collection that stores data in the form of a liked-list. The list is an immutable data structure but may contain duplicate elements. And in real life implementation duplicate elements increase the runtime of the program which is not good. We need to keep a check of duplicate elements are remove them from the list.

So, here we are with the Scala program to remove duplicates from list which can be helpful while working with lists.

Scala – Remove Duplicates from List

There are more than one method that can be used to remove duplicates,

  1. Using distinct method
  2. Converting list into set and then back to list

1) Remove duplicates from list using distinct method

The distinct method is used to extract all distinct elements from a list by eliminating all duplicate value from it.

Syntax

listname.distinct

Example

object myObject { 
	def main(args:Array[String]) {
		val list = List(23, 44, 97, 12, 23, 12 , 56, 25, 76)
		println("The list is : " + list)
		val uniqueList = list.distinct 
		println("The list after removing duplicates is: " + uniqueList)
	} 
} 

Output

The list is : List(23, 44, 97, 12, 23, 12, 56, 25, 76)
The list after removing duplicates is: List(23, 44, 97, 12, 56, 25, 76)

2) Remove duplicates from list by converting list into set and then back to list

One way to remove duplicate elements from a list is by converting the list to another sequence which does not accept duplicates and then convert it back to list.

Syntax

//Converting list to set:
listName.toSet

//Converting set to list:
setName.toList

Example

object myObject{ 
	def main(args:Array[String]) {
		val list = List(23, 44, 97, 12, 23, 12 , 56, 25, 76)
		println("The list is : " + list)
		val seq = list.toSet 
		val uniqueList = seq.toList
		println("The list after removing duplicates is: " + uniqueList)
	} 
}

Output

The list is : List(23, 44, 97, 12, 23, 12, 56, 25, 76)
The list after removing duplicates is: List(56, 25, 97, 44, 12, 76, 23)

Scala List Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.