Q:

Scala program to remove duplicates from list

belongs to collection: Scala List Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)
	} 
}

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to create a range of characters (Lists, Sequen... >>
<< Scala program to access items of List collection u...