【发布时间】:2021-10-18 15:55:05
【问题描述】:
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();
}
}
}
【问题讨论】: