Having an Optional List of Optional's like:
Optional<List<Optional<String>>> optionalList = Optional.of(
Arrays.asList(
Optional.empty(),
Optional.of("ONE"),
Optional.of("TWO")));
How to traverse optionalList to print out the string's ONE and TWO ?
What about having an Optional Stream of Optionals?
Optional<Stream<Optional<String>>> optionalStream = Optional.of(
Stream.of(
Optional.empty(),
Optional.of("ONE"),
Optional.of("TWO")));
Update: Thanks for answers, solution for optionalStream (non nested):
optionalStream
.orElseGet(Stream::empty)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(System.out::println);
Optionalto aStreaminstead of checkingisPresentand getting the value yourself explicitly. Will be a bit more 'functional style'.Optionalin collections, see Uses for Optional and Is it Worth it to Use 'Optional' in Collections?Stream<Optional<T>>which is much more common when the items in your collection are being mapped to anOptional<T>by some other function, so you end up with aStream<Optional<T>>, which you then want to filter and convert to aStream<T>.flatMap()). Finally, I would also avoidOptional<List>andOptional<Stream>as they are not very friendly to work with. Use empty lists/streams instead whenever possible as this makes far cleaner API's.