izhamoidsin
izhamoidsin

Reputation: 133

How to build a collection based on Cartesian product of all elements of other collections?

Can You share any good solution for creating immutable collection in Scala based on full iteration of items in several arrays/another collections?

E.g. in Java you can use:

List<String> signals = ...;
List<SignalState> states = ...;

List<SignalAndState> result = new ArrayList<~>(signals.size() * states.size());

for (String signal: signals) {
  for (SignalState state: states) {
    // some if() condition or process() function can be here 
    result.add(new SignalAndState(signal, state))
  }
}

What are the best practices of building smth like this using Scala? The same approach (using for() in for()) is bad idea, I think, and is not compatible with object-functional nature of Scala language at all.

Upvotes: 4

Views: 255

Answers (1)

jcern
jcern

Reputation: 7848

I am not sure about the best practice, but one way you could accomplish this is to us a use a for comprehension to create the collection you are looking for:

val signals = List[String](...)
val states = List[SignalState](...)

for(signal <- signals; state <- states) yield new SignalAndState(signal, state)

That should yield a List[SignalAndState] with all the elements

Alternately, you could use a flatMap and map to accomplish the same result, like:

signals flatMap ( signal => states map ( state => new SignalAndState(signal, state)))

Upvotes: 5

Related Questions