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,
- Using distinct method
- 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:
Program:
Output:
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:
Program:
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer