0

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Nathan
  • 8,093
  • 8
  • 50
  • 76
  • 1
    Well you should probably create a wrapper class and write your own stream framework – Dici Jan 25 '16 at 17:54
  • You could create a stream with the indices and use `filter` to get the indices you want then map it back to the actual data. For instance printing everything except the last element in an array, `IntStream.range(0, array.length).filter(i -> i != array.length-1).mapToObj(i -> array[i]).forEach(System.out::println);`. But I do not think it is as nice as @LouisWasserman suggestion. – gonzo Jan 25 '16 at 18:27
  • 1
    We're only talking about syntactic sugar here. Not a fan of static methods because they are an anti-pattern for stream syntax. However, if it's just for one method the cost of wrapping everything is not acceptable – Dici Jan 25 '16 at 18:39

1 Answers1

4

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);
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Nathan
  • 8,093
  • 8
  • 50
  • 76
  • 2
    Note that the same feature is suggested in OpenJDK bug tracker (see [JDK-8140283](https://bugs.openjdk.java.net/browse/JDK-8140283)). You may vote for it in [OpenJDK mailing list](http://mail.openjdk.java.net/mailman/listinfo/core-libs-dev) if you like it. – Tagir Valeev Jan 28 '16 at 11:02