【问题标题】:Create collection of cartesian product of two (and more) lists with Java Lambda使用 Java Lambda 创建两个(或更多)列表的笛卡尔积集合
【发布时间】:2016-04-17 14:15:40
【问题描述】:

我可以通过以下方式在 Scala 中轻松实现这一点:

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}

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

我遇到了一些困难,我希望能够将其扩展得更远,因为我希望能够从两个以上的列表中生成许多置换的测试样本。

即使使用流也会不可避免地成为嵌套混乱,还是我自己不够用?

在意识到我在寻找笛卡尔积后发现了一些额外的答案:

How can I make Cartesian product with Java 8 streams?

【问题讨论】:

    标签: java scala lambda for-comprehension


    【解决方案1】:

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

    可以这样写

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

    【讨论】:

      【解决方案2】:

      如果您想避免重复,那么您需要的是组合而不是笛卡尔积。删除重复元素的一种方法是在第二个流之后使用过滤器,如下所示。

      List<Integer> xs = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
      List<Integer> ys = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7));
      
      List<String> combinations =
              xs.stream()
              .flatMap(
                      x -> ys.stream()
                      .filter( y -> x != y)
                      .map(y -> x + ":" + y)
              ).collect(Collectors.toList());
      System.out.println(combinations);
      

      这将为您提供以下信息:

      [1:3, 1:4, 1:5, 1:6, 1:7, 2:3, 2:4, 2:5, 2:6, 2:7, 3:4, 3:5, 3:6, 3:7, 4:3, 4:5, 4:6, 4:7, 5:3, 5:4, 5:6, 5:7, 6:3, 6:4, 6:5, 6:7, 7:3, 7:4, 7:5, 7:6]
      

      我来自未来。我就是这样知道的。 =)

      【讨论】:

        猜你喜欢
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 2014-09-04
        • 2015-10-01
        • 2015-03-09
        • 2020-09-12
        • 2020-07-05
        • 1970-01-01
        相关资源
        最近更新 更多