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 questions and implementations for lists, trees, etc. in all languages.
I've been learning about Java lambdas and trying to use them at every opportunity to get the idiom under my fingers. This question made me wonder: How would I write a custom list or tree so I could use it in all the Java 8 lambda machinery?
All the examples I see use the built in collections. Those work for me. I'm more curious about how a professor teaching data structures ought to rethink their techniques to reflect lambdas and functional programming.
I started with an Iterator
,but it doesn't appear to be fully featured.
Does anyone have any advice?
Note that Java 8 added a new stream() method to the Collection interface. And we can create a stream from individual objects using Stream.
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With