Q:

How to extract unique elements from sequences in Scala?

belongs to collection: Scala Array Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to create a two-dimensional array by... >>
<< Scala program to merge two arrays or array buffer...