scala 去除重复元素
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.
Scala中的List是一个集合,以喜欢列表的形式存储数据。 该列表是不可变的数据结构,但可能包含重复的元素。 在现实生活中,重复元素会增加程序的运行时间,这是不好的。 我们需要检查重复元素是否从列表中删除。
So, here we are with the Scala program to remove duplicates from list which can be helpful while working with lists.
因此,在这里,我们使用Scala程序从列表中删除重复项,这在使用列表时可能会有所帮助。
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
将列表转换为集合,然后返回列表
The distinct method is used to extract all distinct elements from a list by eliminating all duplicate value from it.
通过从列表中消除所有重复值,使用distinct方法从列表中提取所有独特元素。
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)
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)
翻译自: https://www.includehelp.com/scala/remove-duplicates-from-list.aspx
scala 去除重复元素