简体   繁体   English

如何基于其他集合的所有元素的笛卡尔积构建集合?

[英]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? 你可以根据几个数组/其他集合中项目的完整迭代,共享任何在Scala中创建不可变集合的好解决方案吗?

Eg in Java you can use: 例如,在Java中,您可以使用:

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? 使用Scala构建smth的最佳实践是什么? 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. 我认为,相同的方法(在for()中使用for())是个坏主意,并且根本不兼容Scala语言的对象功能。

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: 我不知道最好的做法,但你可以做到这一点的方法之一是我们使用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 这应该产生一个包含所有元素的List[SignalAndState]

Alternately, you could use a flatMap and map to accomplish the same result, like: 或者,您可以使用flatMapmap来完成相同的结果,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM