scala中创建时间序列
While storing data elements to a data structure or extracting raw data duplicate data might be included and this data decreases the efficiency of the code. So, eliminating duplicate data or extracting unique elements is important.
在将数据元素存储到数据结构或提取原始数据时,可能会包含重复数据,并且此数据会降低代码的效率。 因此,消除重复数据或提取唯一元素很重要。
We can extract unique elements from sequences in Scala using two methods,
我们可以使用两种方法从Scala中的序列中提取唯一元素 ,
1)使用独特的方法 (1) Using distinct method)
The distinct method is used to extract unique elements from a collection.
独特的方法用于从集合中提取唯一元素。
Syntax:
句法:
collection_name.distinct
The method returns a collection with unique elements only.
该方法仅返回具有唯一元素的集合。
Program to extract unique elements using distinct method
程序使用独特的方法提取独特的元素
object MyClass {
def main(args: Array[String]) {
val seq = Array(10, 20, 80, 10, 50, 10)
printf("Elements of the Array: ")
for(i <- 0 to seq.length-1)
print(seq(i)+" ")
println()
val uniqueSeq = seq.distinct
printf("The unique elements are: ")
for(i <- 0 to uniqueSeq.length-1)
print(uniqueSeq(i)+" ")
println()
}
}
Output:
输出:
Elements of the Array: 10 20 80 10 50 10
The unique elements are: 10 20 80 50
2)使用toSet方法 (2) Using toSet method)
One more promising solution to the problem is converting the sequence to set. As the set is a collection of all unique elements only all the duplicate elements will be deleted.
解决该问题的另一种有希望的解决方案是将序列转换为set。 由于集合是所有唯一元素的集合,因此仅所有重复元素将被删除。
Syntax:
句法:
sequence.toSet
The method returns a set with all unique elements.
该方法返回具有所有唯一元素的集合。
Program to extract unique elements using set conversion method
程序使用集合转换方法提取唯一元素
object myObject {
def main(args: Array[String]) {
val seq = Array(10, 20, 80, 10, 50, 10)
printf("Elements of the Array: ")
for(i <- 0 to seq.length-1)
print(seq(i)+" ")
println()
val set = seq.toSet
print("Elements of the Array when converted to set: ")
print(set)
}
}
Output:
输出:
Elements of the Array: 10 20 80 10 50 10
Elements of the Array when converted to set: Set(10, 20, 80, 50)
翻译自: https://www.includehelp.com/scala/how-to-extract-unique-elements-from-sequences-in-scala.aspx
scala中创建时间序列