StreamSupport.stream()可以从Iterable创建Stream,但是如果该类实现了Iterable和AutoCloseable呢?是否可以将该类转换为Stream,并在try-with-resources块中构造它?
public class NonWorkingExample {
public static void main(final String[] args) {
// this won't call MyCursor.close()
try (Stream<String> stream = StreamSupport.stream(new MyCursor().spliterator(), false)) {
stream.forEach(System.out::println);
}
}
private static class MyCursor implements AutoCloseable, Iterable<String> {
public void close() throws Exception {
System.out.println("close");
}
public Iterator<String> iterator() {
List<String> items = new ArrayList<>();
items.add("foo");
items.add("bar");
items.add("baz");
return items.iterator();
}
}
}发布于 2021-10-18 16:11:20
作为stated in the javadoc,BaseStream.onClose()“返回一个具有附加关闭处理程序的等价流”:
public class WorkingExample {
public static void main(final String[] args) {
MyCursor cursor = new MyCursor();
try (Stream<String> stream = StreamSupport.stream(cursor.spliterator(), false)
.onClose(cursor::close)) {
stream.forEach(System.out::println);
}
}
}将根据需要调用MyCursor.close()。
https://stackoverflow.com/questions/69619075
复制相似问题