Open In App
Related Articles

Program to apply foreach() method on Java List in Scala

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

constant-time
The method foreach() can be applied on Java list in Scala by utilizing Scala’s JavaConversions object. Moreover, here you need to use JavaConversions object as foreach method is not there in Java language. Now, lets see some examples and then discuss how it works in details. 

Example:1# 

Scala

// Program to apply foreach() method on
// Java List in Scala
 
// Importing Scala's JavaConversions object
import scala.collection.JavaConversions._
 
// Creating object
object GfG
{
 
    // Main method
    def main(args:Array[String])
    {
     
        // Creating list in Java
        val list = java.util.Arrays.asList(7, 5, 2)
         
        // Applying foreach method on
        // the list and displaying
        // output
        list.foreach(println)
 
    }
}

                    
Output:
7
5
2

Time Complexity: O(n) because the foreach method iterates through the entire list of size n and performs a constant-time operation on each element.

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

Therefore, every item of the list is printed when foreach method is applied to the stated list.
 Example:2# 

Scala

// Program to apply foreach() method on
// Java List in Scala
 
// Importing Scala's JavaConversions object
import scala.collection.JavaConversions._
 
// Creating object
object GfG
{
 
    // Main method
    def main(args:Array[String])
    {
     
        // Creating list in Java
        val list = java.util.Arrays.asList(11, 12, 13)
         
        // Applying foreach method on
        // the list and displaying
        // output
        list.foreach(println)
     
    }
}

                    
Output:
11
12
13

It is same as above example but here the elements of the list are not present in proper order.

Time Complexity: O(n) because the foreach method iterates over all the elements  in the list and performs the specified operation (in this  case, printing the element to the console) on each element.  The time complexity is directly proportional to the  number of elements in  the list, so the time complexity is O(n) where n is the number of elements in the list.

Auxiliary Space: O(1) because the space complexity is not affected by the size of the input (the list) and only a constant amount of space is required to store the variables and intermediate values used during the execution of the program.



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