Home » Scala » Scala array programs

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

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.

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

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)





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.