Conversion from a Java Set to a Scala Set
A Java Set can be converted to a Scala Set by importing JavaConversions.asScalaSet method. Here, we need to call asScalaSet method which has a java Set as its argument. Therefore, this method returns a Scala Set.
Now, lets see some examples.
Example:1#
import scala.collection.JavaConversions.asScalaSet
object GfG
{
def main(args : Array[String])
{
val jlist = java.util.Arrays.asList( 14 , 15 , 16 )
val jSet = new java.util.HashSet[Int]()
val x = jSet.addAll(jlist)
val results = asScalaSet(jSet)
println(results)
}
}
|
So, a Scala Set is returned here. In the above example firstly, we have created a Java list then we have declared a Java Set Where, we have added all the elements of the Java list to the Java Set utilizing addAll method. After that the stated Java Set is converted to a Scala Set utilizing asScalaSet method.
Lets see one more example.
Example:2#
import scala.collection.JavaConversions.asScalaSet
object GfG
{
def main(args : Array[String])
{
val jlist = java.util.Arrays.asList( 11 , 9 , 5 )
val jSet = new java.util.HashSet[Int]()
val x = jSet.addAll(jlist)
val results = asScalaSet(jSet)
println(results)
}
}
|
Therefore, here also a Set is returned. Moreover, the list stated here is given in a proper order but a Set needs to be in a proper order so, the Set which is returned as output is in proper order.
Last Updated :
21 Nov, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...