Nis*_*mar 5 java arrays java-8 java-stream
我正在使用以下代码重用 Stream 但得到
java.lang.IllegalStateException: 流已经被操作或关闭
代码
public static void main(String[] args) {
try {
String[] array = { "a", "b", "c", "d", "e" };
Stream<String> ss = Stream.of(array);
Supplier<Stream<String>> streamSupplier = () -> ss;
long count = streamSupplier.get().count();
// get new stream
streamSupplier.get().forEach(x -> System.out.println(x));
// get another new stream
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
不要分配Stream.of(array)给中间变量,只需直接在Supplier:
Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);
Run Code Online (Sandbox Code Playgroud)
那是因为以前您只会在调用时始终提供相同的引用,supplier.get()但实际上您想返回一个新的Stream.
同样正如@Eugene 所建议的那样,首选使用Arrays.stream()over Stream.of()。因为后者是一个可变参数方法,但只是委托给前者。
也可以使用以下Stream.peek()方法简化您当前的方法:
long count = Arrays.stream(array)
.peek(System.out::println)
.count();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1258 次 |
| 最近记录: |