How to implement a Java stream?

后端 未结 5 905
悲哀的现实
悲哀的现实 2020-12-01 06:34

I want to implement a Stream.

I don\'t want to just use implements Stream, because I would have to implement a ton of met

5条回答
  •  囚心锁ツ
    2020-12-01 06:50

    If you're wanting to make your own Stream because you want custom close() logic, the simplest solution is to create a Stream from an Iterator, and call onClose(Runnable). For instance, to stream from a Reader via Jackson:

    MappingIterator values = objectMapper.reader(type).readValues(reader);
    return StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(values, Spliterator.ORDERED), false)
            .onClose(() -> {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
    

提交回复
热议问题