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

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.

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

Program:

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

Program:

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)





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.