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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


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#



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.