Program to convert Java Set of strings to a Traversable in Scala
Last Updated :
03 Jan, 2020
A java Set of strings can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work.
Now, lets see some examples and then discuss how it works in details.
Example:1#
import scala.collection.JavaConversions. _
object GfG
{
def main(args : Array[String])
{
val set = new java.util.HashSet[String]()
set.add( "i" )
set.add( "am" )
set.add( "good" )
val tra = set.toTraversable
println(tra)
}
}
|
Here, the stated output is in same order as stated in the given set.
Example:2#
import scala.collection.JavaConversions. _
object GfG
{
def main(args : Array[String])
{
val set = new java.util.HashSet[String]()
set.add( "i" )
set.add( "am a" )
set.add( "girl" )
val tra = set.toTraversable
println(tra)
}
}
|
Output:
Set(am a, i, girl)
Here, the strings with more number of words are displayed first and strings of greater length are displayed at last.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...