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);
` and `Optional` as they are not very friendly to work with. Use empty lists/streams instead whenever possible as this makes far cleaner API's.
– Didier L Aug 03 '18 at 16:02` is not really considered good practice... ideally one returns an empty `List`, however I did encounter some cases where there was a difference between returning an empty list and not returning one at all. (Traditionally it would be returning a `null` instead of empty list.) Ideally one avoids this because it is confusing to the reader, but sometimes situations do arise which put you in a corner.
– jbx Aug 06 '18 at 08:23