scala中创建时间序列_如何从Scala中的序列中提取唯一元素?

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中创建时间序列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值