How To Use Classic Custom Data Structures As Java 8 Streams

后端 未结 2 1019
心在旅途
心在旅途 2021-02-10 09:52

I saw a SO question yesterday about implementing a classic linked list in Java. It was clearly an assignment from an undergraduate data structures class. It\'s easy to find qu

相关标签:
2条回答
  • 2021-02-10 10:29

    Exposing a stream view of arbitrary data structures is pretty easy. The key interface you have to implement is Spliterator, which, as the name suggests, combines two things -- sequential element access (iteration) and decomposition (splitting).

    Once you have a Spliterator, you can turn that into a stream easily with StreamSupport.stream(). In fact, here's the stream() method from AbstractCollection (which most collections just inherit):

    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
    

    All the real work is in the spliterator() method -- and there's a broad range of spliterator quality (the absolute minimum you need to implement is tryAdvance, but if that's all you implement, it will work sequentially, but will lose out on most of the stream optimizations.) Look in the JDK sources Arrays.stream(), IntStream.range()) for examples of how to do better.)

    0 讨论(0)
  • 2021-02-10 10:40

    I'd look at http://www.javaslang.io for inspiration, a library that does exactly what you want to do: Implement custom lists, trees, etc. in a Java 8 manner.

    It specifically doesn't closely couple with the JDK collections outside of importing/exporting methods, but re-implements all the immutable collection semantics that a Scala (or other FP language) developer would expect.

    0 讨论(0)
提交回复
热议问题