【问题标题】:Is it possible to apply a BiFunction across 2 streams [duplicate]是否可以跨 2 个流应用 BiFunction [重复]
【发布时间】:2019-10-20 12:48:58
【问题描述】:

例如,我想要这样的东西:

n = {1, 2, 3, 4, 5}
m = {1, 2, 3, 4, 5}
x = Arrays.stream(n);
y = Arrays.stream(n);
IntStream.multiply(x,y) // int stream now containing squares

我想避免这样做:

Intstream.range(0, x.count())
.map(i-> {
    z= biFunction.apply(
        x.findFirst().get(),
        y.findFirst().get()
    );
    x.skip(1);
    y.skip(1);
    return z;
})

(创建一个 int-stream,仅用于索引)。

【问题讨论】:

  • 不幸的是,我认为这是不可能的。 Java 流并不适用于所有计算情况。您必须使用提供的示例(我个人认为这看起来不太糟糕)。
  • 我宁愿简单地使用数组
  • 一切由你决定。流解决方案肯定更优雅,但直接数组访问性能更高。
  • 本示例的预期输出是什么?
  • @Tobiq 即使你有这样的BiFunction 比如Math::multiplyExact 来计算两个数字的乘积。必须以某种方式指定数字的索引。

标签: java java-stream


【解决方案1】:

这是可能的,但我很难想象一个值得这样做的情况。我们在产品上构造一个迭代器,将其转换为拆分器,然后转换为流。

    int[] n = {1, 2, 3, 4, 5};
    int[] m = {1, 2, 3, 4, 5};
    IntStream x = Arrays.stream(n);
    IntStream y = Arrays.stream(m);
    PrimitiveIterator.OfInt nIt = x.iterator();
    PrimitiveIterator.OfInt mIt = y.iterator();

    Iterator<Integer> prodIterator = new Iterator<>() {

        @Override
        public boolean hasNext() {
            return nIt.hasNext() && mIt.hasNext();
        }

        @Override
        public Integer next() {
            // Apply your BiFunction here
            return nIt.next() * mIt.nextInt();
        }
    };

    Iterable<Integer> prodIterable = () -> prodIterator;

    Stream<Integer> productStream = StreamSupport.stream(prodIterable.spliterator(), false);

    productStream.forEach(System.out::println);

输出:

1
4
9
16
25

如果您想要 IntStream,我相信您可以自己拆箱 Stream&lt;Integer&gt;

请注意,如果原始流中有不同数量的元素,则较长流中的额外元素将被默认忽略,这可能不是您想要的。请想出更好的办法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多