Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over an optional list of integers ifPresent

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.

like image 634
aayush_v20 Avatar asked Apr 12 '17 23:04

aayush_v20


2 Answers

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());
like image 100
ZhekaKozlov Avatar answered Sep 17 '22 13:09

ZhekaKozlov


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);
like image 21
Jeremy Grand Avatar answered Sep 21 '22 13:09

Jeremy Grand