Open In App

Program to print Java List in Scala

Improve
Improve
Like Article
Like
Save
Share
Report

A java list 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




// Scala program to print Java List
// 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
         val list = new java.util.ArrayList[Int]()
 
         // Adding elements in the List
         list.add(11)
         list.add(12)
 
               // Displays output
               println(list)
                           }
 
// Assigning result method to list
val list = result
  }
}


Output:

[11, 12]

Time Complexity: O(1) because the only operation being performed is the creation of a new Java ArrayList and adding two elements to it, both of which are constant-time operations

Auxiliary Space:  O(1) because the only variables being used are a few integers and a reference to the Java ArrayList, which are all constant in size regardless of the input size.

Therefore, a list 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 elements of the list to the stated list one after another and then prints the results. Example:2# 

Scala




// Scala program to print Java List
// 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
         val list = new java.util.ArrayList[Int]()
 
         // Adding elements in the List
         list.add(11)
         list.add(12)
         list.add(17)
 
               // Displays output
               println(list)
                           }
 
// Assigning result method to list
val list = result
  }
}


Output:

[11, 12, 17]

It is same as above example but here one more element is added in the stated list.

Time Complexity: O(1), as it only performs a few constant-time operations such as creating an ArrayList object and adding a few elements to it.
Auxiliary Space: O(1), as it does not use any additional data structures and only creates a single java ArrayList object.



Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads