Wednesday 4 May 2022

Scala Function - aggregateExample

Scala Collection - aggregateExample

Use with Par function - It will split input in multiple collection and execute them parallel into 2 steps, first is sequence op and second is combine operation.

If we are not using aggregate with par function then we should use foldLeft.


object MyBlog {  
  def main(args: Array[String]): Unit = {  
   aggregateExample(List(1,2,3,4))  
  }  
  def aggregateExample(input: List[Int]): Unit = {  
   //Aggregate should be used with par to execute input parallel. input.par.aggregate  
   val output = input.aggregate((0,0))(  
    (acc, element) => (acc._1 + element, acc._2 + 1), // (1,1) (2,1) (3,1)(4,1)  
    (accu, element) => (accu._1 + element._1, accu._2 + element._2) // (1+2+3+4) (1+1+1+1) (10,4)  
   )  
   println("Output: " + output) // (10,4)  
   //Use foldLeft if we are not using par.  
   val outputWithFoldLeft = input.foldLeft((0,0))((acc,ele) => (acc._1 + ele, acc._2 + 1) )  
   println("Output with FoldLeft: " + outputWithFoldLeft) //(10,4)  
  }  
 }  




No comments:

Post a Comment