I have an Optional list of integers. I wish to see if the list is actually present and then convert it into a stream. One way of doing this is
Optional<List<Integer>> listOfNumbers = ...
if (listOfNumbers.isPresent()) {
listOfNumbers.get().stream();
}
But, I dont wish to have that if condition. I searched and saw that ifPresent()
does the same thing but when I do listOfNumbers.ifPresent(this::get))
, I get the following error:
non-static variable this cannot be referenced from a static context
Can you please help me do this in an efficient manner? This is still new to me so if there's anything incorrect in my understanding please let me know.
As pointed in the comments, the cleanest way to get a Stream
is to use Optional.orElse
method with Collections.emptyList
:
Stream<Integer> stream = listOfNumbers.orElse(Collections.emptyList()).stream();
The other possible solution with Optional.map
:
Stream<Integer> stream = listOfNumbers.map(List::stream).orElse(Stream.empty());
Update Java 9 :
Since jdk9, Optional
has a new method stream()
, which returns either a stream of one element, or an empty stream.
Thus, going from an Optional<List<Integer>>
to an Stream<Integer>
becomes
Stream<Integer> streamOfNumbers = listOfNumbers.stream().flatMap(List::stream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With