交叉连接两个列表 java

Cross join two lists java

我有一个 class ABC,其中包含两个整数字段

public class ABC{
  private Integer x;
  private Integer y;

   // getters and setters
}

我有两个列表:xValues 和 yValues,它们分别包含 x 和 y 值的整数列表。

List<Integer> xValues = fetchAllXValues();  //say list xValues contains {1,2,3}
List<Integer> yValues = fetchAllYValues();  //say list yValues contains {7,8,9}

现在我想要的是使用 xValues 列表的每个值和 yValues 列表的每个值创建一个 ABC 对象。我不想使用嵌套的 for 循环。解决这个问题的更有效方法是什么?

ABC 的示例输出对象是:

     ABC(1,7);
     ABC(1,8);
     ABC(1,9);
     ABC(2,7);
     ABC(2,8);
     ABC(2,9);
     ABC(3,7);
     ABC(3,8);
     ABC(3,9);

遍历第一个列表,每次迭代遍历第二个列表:

xValues.stream()
    .flatMap(x -> yValues.stream().map(y -> new ABC(x, y)))
    .collect(toList());

如果您愿意使用第三方库,则可以使用 Eclipse Collections,它具有丰富而简洁的 API,可直接在集合下使用。

MutableList<Integer> xValues = ListAdapter.adapt(fetchAllXValues());  
MutableList<Integer> yValues = ListAdapter.adapt(fetchAllYValues());  

xValues.flatCollect(x -> yValues.collect(y -> new ABC(x, y)));

flatCollect()这里相当于Java8个流flatMap()。同样 collect() 等价于 map()

注意:我是 Eclipse Collections 的提交者。

要解决这个问题,您还可以使用一些外部库,例如使用 StreamEx,它看起来像:

    StreamEx.of(xValues).cross(yValues)
      .map(entry -> new ABC(entry.getKey(), entry.getValue()))
      .collect(Collectors.toList());