Is there a class in Java 8 that implements “null termination” flow without scrolling?
Or is there a better way to do this? I'm missing? I want to create a vendor - based (usually unrestricted) flow, but when the vendor returns null, the flow will terminate I did this myself, but it seems quite a lot of work to complete a simple concept
public class NullTerminatedStreamFactory { static int characteristics = Spliterator.ORDERED | Spliterator.DISTINCT; public static<T> Stream<T> makeNullTerminatedStream(supplier<T> supplier) { return StreamSupport.stream(new NullTerminatedSpliteratorFromsupplier<>(supplier,Long.MAX_VALUE,characteristics),false); } static class NullTerminatedSpliteratorFromsupplier<T> extends Spliterators.AbstractSpliterator<T> { public NullTerminatedSpliteratorFromsupplier(supplier<T> supplier,long est,int additionalcharacteristics) { super(est,additionalcharacteristics); this.supplier = supplier; } public supplier<T> supplier; @Override public boolean tryAdvance(Consumer<? super T> action) { T next = supplier.get(); if (next != null) { action.accept(next); return true; } return false; } } }
For recording purposes, I am using it to basically create a stream from BlockingQueue:
NullTerminatedStreamFactory.makeNullTerminatedStream(() -> { try { BlockingQueue<Message> queue = getBlockingQueue(); return queue.poll(1,TimeUnit.SECONDS); } catch (Exception e) { log.error("Exception while trying to get message from queue",e); } return null; });
Solution
You have found a perfect and effective manual implementation
As mentioned in the comments, Java 9 seems to have added a takeWhile (predict) method Before that, you can use a third-party library that implements takewhile():
jOO λ
jOO λ There is limitwhile (), which does the same thing:
Seq.generate(supplier).limitWhile(Objects::nonNull);
(disclaimer, I'm Joo λ Later company work)
Javaslang
Javaslang implements its own stream class, which is inspired by Scala collections and therefore comes with widget ()
Stream.gen(supplier).takeWhile(Objects::nonNull);
Functional Java
Functional Java also has its own stream implementation, which has a takeWhile () method:
Stream.fromFunction(i -> supplier.get()).takeWhile(o -> o != null);