Search code examples
javajava-streamfunctional-interface

How to create a Supplier from another Supplier and filter out some items?


Suppose Supplier<Optional<Item>> is the source and Supplier<Item> is what we want: the same items without Optional.Empty cases.


Solution

  • Inspired by Boris and khelwood:

    Supplier<Item> filtered = Stream.generate(optSupplier)
            .flatMap(Optional::stream)
            .iterator()::next;
    

    If you're pre-Java 9, replace flatMap with .filter(Optional::isPresent).map(Optional::get).