A java Set of characters can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, you 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#
// Scala program to convert Java set // to a Traversable in Scala // Importing Scala's JavaConversions object import scala.collection.JavaConversions. _
// Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating set of characters in Java
val set = new java.util.HashSet[Char]()
// Adding characters to the set
set.add( 'x' )
set.add( 'y' )
set.add( 'z' )
// Converting set to a Traversable
val tra = set.toTraversable
// Displays traversable
println(tra)
}
} |
Output:
Set(x, y, z)
Here, the stated output is in same order as stated in the given set.
Example:2#
// Scala program to convert Java set // to a Traversable in Scala // Importing Scala's JavaConversions object import scala.collection.JavaConversions. _
// Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating set of characters in Java
val set = new java.util.HashSet[Char]()
// Adding characters to the set
set.add( 'g' )
set.add( 'f' )
set.add( 'e' )
// Converting set to a Traversable
val tra = set.toTraversable
// Displays traversable
println(tra)
}
} |
Output:
Set(e, f, g)
Here, the stated set is not given in proper order but the resultant output is in proper order.