Home > database >  Scala generate a cummulative set of elements by looping over list of objects which returns sets in e
Scala generate a cummulative set of elements by looping over list of objects which returns sets in e

Time:08-29

I have a list of objects like [obj1,obj2,obj3...objn]. I want to run the below snippet on each object of the list and want to find a cummulative set of type Set[a,b] which contains the output set of all obj1,obj2....objn

{
val x = Function1(obj)
Function2(x) ***//this returns a Set of type Set[a,b]*** 
}

Can someone please help me with this?

CodePudding user response:

Sounds like you require a flatMap:

val rez = mylist.flatMap(obj => function2(function1(obj)))

CodePudding user response:

You will want to use map or fold on your input list.

Something like this:

list.foldLeft(Set()) { case (acc, obj) =>
  val set = function2(function1(obj))
  acc    set // or other logic to combine the Sets
}

Note the above fold is the same as just using flatMap.

  • Related