While working with Java 8 Streams, I some times find that Stream doesn't have a particular method that I desire (e.g. takeWhile(), dropWhile(), skipLast()
). How do I create my own stream class which has the additional methods with out re-writing the entire Java 8 Stream architecture?
I am aware of the StreamEx library and know that it has takeWhile() and dropWhile(). As of writing this, it doesn't have skipLast()
. I have filed an issue for this method.
An acceptable solution would be to show how Java 8 Stream or StreamEx can be extended.
Since version 0.5.4 StreamEx library has a chain()
method. This allows for creating helper methods which plug in comfortably.
public static <T> UnaryOperator<StreamEx<T>> skipLast(int n)
{
return(stream -> skipLast(stream, n));
}
private static StreamEx<T> skipLast(Stream<T> input, int n)
{
// implement the real logic of skipLast
}
With the above, one can now write...
StreamEx.
of(input).
chain(skipLast(10)).
forEach(System.out::println);