Open In App

Conversion from a Java Set to a Scala Set

Last Updated : 21 Nov, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
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# Scala
// Scala program of converting a Java Set
// to a Scala Set

// Importing JavaConversions.asScalaSet
import scala.collection.JavaConversions.asScalaSet

// Creating object
object GfG
{ 

    // Main method
    def main(args:Array[String])
    {
    
        // Creating a Java List
        val jlist = java.util.Arrays.asList(14, 15, 16)
        
        // Creating a java Set
        val jSet = new java.util.HashSet[Int]()
        
        // Adding all the elements of the
        // list to the set
        val x = jSet.addAll(jlist)
        
        // Converting from java Set
        // to Scala Set
        val results = asScalaSet(jSet)
        
        // Displays results
        println(results)
    }
}
Output:
Set(14, 15, 16)
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# Scala
// Scala program of converting a Java list
// to a Scala Buffer

// Importing JavaConversions.asScalaSet
import scala.collection.JavaConversions.asScalaSet

// Creating object
object GfG
{ 

    // Main method
    def main(args:Array[String])
    {
    
        // Creating a Java List
        val jlist = java.util.Arrays.asList(11, 9, 5)
        
        // Creating a java Set
        val jSet = new java.util.HashSet[Int]()
        
        // Adding all the elements of the
        // list to the set
        val x = jSet.addAll(jlist)
        
        // Converting from java Set
        // to Scala Set
        val results = asScalaSet(jSet)
        
        // Displays results
        println(results)
    }
}
Output:
Set(5, 9, 11)
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.

Next Article

Similar Reads