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

Can you share any good solution for creating an immutable collection in Scala based on a complete iteration of elements in multiple arrays / other collections?

eg. 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 methods for building smth like this using Scala? The same approach (using for () in for ()) is a bad idea, I think, and is not compatible with the object-functional nature of Scala in general.

+4
source share
1 answer

I'm not sure about the best practice, but one way to achieve this is to use a for understanding 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) 

This should give a List[SignalAndState] with all elements

Alternatively, you can use flatMap and map to achieve the same result, for example:

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

Source: https://habr.com/ru/post/1445045/


All Articles