【问题标题】:Converting an AutoCloseable, Iterable class into a Stream将 AutoCloseable、Iterable 类转换为 Stream
【发布时间】:2021-10-18 15:55:05
【问题描述】:

StreamSupport.stream() 可以从Iterable 创建一个Stream,但是如果该类实现IterableAutoCloseable 会怎样?是否可以将该类转换为 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();
        }
    }
}

【问题讨论】:

    标签: java-stream autocloseable


    【解决方案1】:

    As 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()

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 2010-11-07
      • 2018-10-09
      • 2019-11-08
      • 2014-09-19
      • 2022-11-28
      相关资源
      最近更新 更多