gpt4 book ai didi

java-8 - Java 8 流已被操作或关闭

转载 作者:行者123 更新时间:2023-12-02 02:58:05 26 4
gpt4 key购买 nike

我正在尝试执行操作并将这些值添加到 int[] 中。

我在流中收集了这些值,但是在打印这些值时,我收到流已关闭的异常。

我的代码如下:

import java.util.*;
import java.util.stream.*;
import java.util.function.Supplier;
public class Main
{
public static void main (String[]args)
{
IntStream mystream = IntStream.of (3, 4, 5, 9, 18, 54, 8, 7, 14, 3);
Stream < int[] > p =
mystream.boxed ().flatMap (a->mystream.mapToObj (b->{
return new int[]{a, b,
(int)
Math.
sqrt ((a * a) + (b * b))};}));

Supplier < Stream < int[] >> streamSupplier = ()->p;

streamSupplier.get ().forEach (t->System.out.
println (t[0] + ", " + t[1] +
", " + t[2]));
}
}

下面是我收到的错误: enter image description here

最佳答案

您正在尝试使用 IntStream引用者mystream多次。

以下操作将消除该错误:

Stream<int[]> p =
mystream.boxed ()
.flatMap (a->IntStream.of (3, 4, 5, 9, 18, 54, 8, 7, 14, 3)
.mapToObj (b->new int[]{a, b, (int) Math.sqrt (a*a + b*b)}));

也就是说,我也会删除你的 Supplier<Stream<int[]>>实例,并在p上进行操作Stream直接(即 p.forEach(...) ),因为它只能被消耗一次,所以用 Supplier 包装它是没有意义的。 .

关于java-8 - Java 8 流已被操作或关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60633611/

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