gpt4 book ai didi

java - 通过组合多个流的结果创建一个流

转载 作者:行者123 更新时间:2023-11-30 06:52:09 27 4
gpt4 key购买 nike

如何将多个流转换为一个流?例如,我有 3 个 IntStreams,我想将它们组合成一个 int 数组 Stream。

在 Javadoc 中,大多数 Stream 操作都将一个流作为输入,concat 没有回答我的用例。

这是我的想法

Stream 1: 1, 2, 3
Stream 2: 4, 5, 6
Combined Stream ex1: [1,4],[2,5],[3,6]
Combined Stream ex2: 1+4,2+5,3+6
Combined Stream ex3: new MyObject(1,4), new MyObject(2,5), new MyObject(3,6)

最佳答案

在功能方面,问题归结为压缩流列表,并为每个元素应用自定义 zipper 。

There is no facility直接使用 Stream API 来做到这一点。我们可以使用第三方库,比如 protonpack库,它提供了一个 zip 方法来做到这一点。考虑数据:

List<Stream<Integer>> streams = Arrays.asList(Stream.of(1,2,3), Stream.of(4,5,6));

你可以拥有

Stream<Integer> stream = StreamUtils.zip(streams, l -> l.stream().mapToInt(i -> i).sum());
// the Stream is now "1+4,2+5,3+6"

Stream<Integer[]> stream = StreamUtils.zip(streams, l -> l.toArray(new Integer[l.size()]));
// the Stream is now "[1,4][2,5][3,6]"

映射器获取要压缩的元素列表并返回压缩后的值。在第一个示例中,它将值相加,而在第二个示例中返回一个数组。

关于java - 通过组合多个流的结果创建一个流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com