交叉连接两个列表java

时间:2016-07-25 13:02:53

标签: list java-8 nested-loops

我有一个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);

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

如果您愿意使用第三方库,则可以使用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()这相当于Java 8流flatMap()。同样,collect()相当于map()

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

答案 2 :(得分:0)

要解决此问题,您还可以使用一些外部库,例如使用StreamEx,它将如下所示:

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