Open In App

Program to print Java Set of Strings in Scala

Last Updated : 29 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

A java Set of strings can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don’t even need to import any Scala’s JavaConversions object in order to make this conversions work.
Now, lets see some examples.
Example:1#




// Scala program to print Java Set 
// of strings in Scala
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a java method in Scala
        def res = {
          
                // Creating a java Set of strings
                val set = new java.util.HashSet[String]()
          
                // Adding strings to the Set 
                set.add("Nidhi")
                set.add("Nisha")
          
                    // Displays output
                    println(set)
                                }
          
        // Assigning result method to set of strings
        val set = res
    }
}


Output:

[Nidhi, Nisha]

Therefore, a set of strings is returned from a Java method. Here, we don’t need to import any object of Scala. In the above program a Java method is written in Scala program. Where, this method adds the string elements of the Set to the stated set one after another and then prints the results.
Example:2#




// Scala program to print Java Set 
// of strings in Scala
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a java method in Scala
        def res = {
          
                // Creating a java Set of strings
                val set = new java.util.HashSet[String]()
          
                // Adding strings to the Set
                set.add("nidhi")
                set.add("is an")
                set.add("author")
          
                    // Displays output
                    println(set)
                                }
          
        // Assigning result method to set
        val set = res
    }
}


Output:

[nidhi, author, is an]

It is same as above example but here one more element is added in the stated set of strings and as it is a set so, the order of the elements is maintained. Hence, the elements with more number of words are printed later than the one with lesser words.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads