scala 去除重复元素_Scala程序从列表中删除重复项
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
將列表轉換為集合,然后返回列表
1)使用獨特的方法從列表中刪除重復項 (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.
通過從列表中消除所有重復值,使用distinct方法從列表中提取所有獨特元素。
Syntax:
句法:
listname.distinctProgram:
程序:
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)通過將列表轉換為集合,然后返回列表,從列表中刪除重復項 (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.toListProgram:
程序:
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.toListprintln("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 去除重復元素
總結
以上是生活随笔為你收集整理的scala 去除重复元素_Scala程序从列表中删除重复项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ruby array_Ruby中带有示例
- 下一篇: 数据分析 数据科学_数据科学中的数据分析