Open In App

Program to print Java List of Strings in Scala

Last Updated : 02 Dec, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

A java list of strings can be returned from a Scala program by writing a user defined method of Java in Scala. Here, you 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 List 
// of strings in Scala
  
// Creating object
object GfG
  
// Main method
def main(args:Array[String])
{
  
    // Creating a java method in Scala
    def result = {
      
        // Creating a java list of strings
        val list = new java.util.ArrayList[String]()
      
        // Adding string elements in the List
        list.add("gfg")
           list.add("cs")
    
           // Displays output
           println(list)    }
      
    // Assigning result method to list
    val list = result
}
}


Output:

[gfg, cs]

Therefore, a list of strings is returned from a Java method. Here, you 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 list to the stated list one after another and then prints the results.
Example:2#




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


Output:

[Nidhi, is an, author]

It is same as above example but here one more element is added in the stated list and here proper order of the elements is not required.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads