Go Back

how to remove duplicate elements in String in scala

6/17/2023
All Articles

#scala #program #removeDuplicate #code

how to remove duplicate elements in String in  scala

how to remove duplicate elements in String in  scala

If we try to covert  String to Array   then  remove duplicate value using Distinct method .

Finally we print contents of an Array in scala we’ll have a surprise output :

        var ls= "shubham" 
        var array= ls.toCharArray
        array.distinct.foreach(print)

 

Conclusion 

 
While List, Set, and Map are actual Scala collections, 
the Array type is just the Scala equivalent of Java native arrays (e.g., String[] to represent a native array of Strings). 
So when we try to use method distinct in scala and print content of  array ,
 we used foreach loop to print element because  toString method give only whatever is defined in the Array.toString method (usually is the object hashcode, but it depends on the platform).
 

Article