使用Java Lambda创建两个(和更多)列表的笛卡尔积的集合 [英] Create collection of cartesian product of two (and more) lists with Java Lambda

查看:1103
本文介绍了使用Java Lambda创建两个(和更多)列表的笛卡尔积的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在Scala中轻松实现这一点,例如:

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)
}

所以,如果我给它{1,2},{3,4}我返回{1,3},{1,4},{2,3},{2,4}

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

我希望能够使用流将其转换为java 8.

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.

即使使用流还是am,它是否会不可避免地成为嵌套的混乱我没有足够自我申请?

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:

如何使用Java 8流制作笛卡尔积?

推荐答案

我很难搞清楚你希望的是什么,看起来就像你想要获得笛卡尔产品一样T'比如,给定 {1,2} {3,4} ,你期待 {(1,3),(1,4),(2,3),(2,4)} ? (对于它的价值,我认为这与排列的数学定义没有任何关系,排列通常涉及对单个列表的内容进行排序的不同方式。)

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.)

那可以写成

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

这篇关于使用Java Lambda创建两个(和更多)列表的笛卡尔积的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆