Create collection of cartesian product of two (and

2019-02-20 22:31发布

问题:

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());