这里是一个使用两个 int
数组作为源而不是 List<Integer>
的 IntStream
解决方案。我想知道是否有可能解决这个问题,而不必将每个 int
包装为 Integer
。
int[] one = new int[]{1, 2, 3};
int[] two = new int[]{3, 4};
List<IntIntPair> list = new ArrayList<>();
IntStream.of(one).forEach(i ->
IntStream.of(two).mapToObj(j -> PrimitiveTuples.pair(i, j)).forEach(list::add));
System.out.println(list);
很遗憾,我无法在IntStream
上使用flatMap
,因为它返回一个IntStream
。目前IntStream
上没有flatMapToObj
,这是需要的。所以我使用了forEach
。
我使用了IntIntPair
和PrimitiveTuples
类来自于Eclipse Collections,因为它们使输出列表作为字符串更简单。您可以像您在解决方案中所做的那样使用int[]
。 代码如下。
List<int[]> list = new ArrayList<>();
IntStream.of(one).forEach(i ->
IntStream.of(two).mapToObj(j -> new int[]{i, j}).forEach(list::add));
在即将于3月中旬发布的Eclipse Collections 8.1版本中,所有基本容器都新增了一个
flatCollect
方法,可用于解决这个问题。它本质上实现了在
IntStream
上应该有的
flatMapToObj
方法。
IntList a = IntLists.mutable.with(1, 2, 3)
IntList b = IntLists.mutable.with(3, 4)
List<IntIntPair> result =
a.flatCollect(
i -> b.collect(j -> PrimitiveTuples.pair(i, j)),
Lists.mutable.empty())
System.out.println(result)
// [1:3, 1:4, 2:3, 2:4, 3:3, 3:4]
更新:
正如Boris the Spider在评论中指出的那样,forEach
解决方案在多线程时不是线程安全的,如果IntStream
为parallel
,则会出现问题。以下解决方案可在串行或并行环境中使用。我很高兴有人指出这一点,因为我原来没有想到需要对 IntStream
进行 mapToObj
, 然后再接着使用flatMap
。
int[] one = new int[]{1, 2, 3};
int[] two = new int[]{3, 4};
List<int[]> list = IntStream.of(one).parallel()
.mapToObj(i -> IntStream.of(two).mapToObj(j -> new int[]{i, j}))
.flatMap(e -> e)
.collect(Collectors.toList());
list.stream().map(e -> "{" + e[0] + "," + e[1] + "}").forEach(System.out::println);
注意:我是 Eclipse Collections 的贡献者。