Create collection of cartesian product of two (and more) lists with Java Lambda

我的未来我决定 提交于 2019-12-19 10:45:36

问题


I'm able to easily achieve this in Scala with something like:

def permute(xs: List[Int], ys: List[Int]) = {
  for {x <- xs; y <- ys} yield (x,y)
}

So if I give it {1, 2}, {3, 4} I return {1, 3}, {1, 4}, {2, 3}, {2, 4}

I was hoping to be able to translate this to java 8 using streams.

I'm having a bit of difficulty and I'd like to be able to extend this out farther as I'd like to be able to generate many permuted test samples from more than two lists.

Will it inevitably be a nested mess even using streams or am I not applying myself enough?

Some additional answers were found after realizing that I was looking for a cartesian product:

How can I make Cartesian product with Java 8 streams?


回答1:


I'm having difficulty figuring out what you're hoping for, it looks like you're trying to get a Cartesian product? Like, given {1, 2} and {3, 4}, you're expecting {(1, 3), (1, 4), (2, 3), (2, 4)}? (For what it's worth, I don't think that has any relationship to the mathematical definition of permutations, which generally involve different ways of ordering the contents of a single list.)

That could be written

xs.stream()
  .flatMap(x -> ys.stream().map(y -> Pair.of(x, y)))
  .collect(toList());


来源:https://stackoverflow.com/questions/34752575/create-collection-of-cartesian-product-of-two-and-more-lists-with-java-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!