How to extract unique elements from sequences in Scala?

Here, we are going to learn how to extract unique elements from sequences in Scala programming language?
Submitted by Shivang Yadav, on April 14, 2020 [Last updated : March 10, 2023]

Scala – Extracting Unique Elements from a Sequences

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,

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.

Scala code 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) 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.

Syntax

    sequence.toSet

The method returns a set with all unique elements.

Scala code 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)

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.