w3resource

Scala Programming: Remove duplicate elements from an array of strings

Scala Programming Array Exercise-17 with Solution

Write a Scala program to remove duplicate elements from an array of strings.

Sample Solution:

Scala Code:

object Scala_Array {   
   def main(args: Array[String]): Unit = {     
       var my_array = Array("bcd", "abd", "jude", "bcd", "oiu", "gzw", "oiu");
       println("Orginal array:")
       for ( x <- my_array) {
         print(s"${x}, ")        
        }      

        var f =0
        for (i <- 0 to my_array.length-1)
         {
           var x = f+1;
           for (j <- x to my_array.length-1)
            {
                if(my_array(f) == my_array(x) && (f != x) )
                {
                    println("\nDuplicate Element: "+my_array(x));
                }
              x=x+1;
            }
           f=f+1;
        }
       }
}

Sample Output:

Orginal array:
bcd, abd, jude, bcd, oiu, gzw, oiu, 
Duplicate Element: bcd
Duplicate Element: oiu

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the common elements between two arrays of strings.
Next: Write a Scala program to remove duplicate elements from an array of integers.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.