I want to save the return value of a method and use it to create a new object with which ill add to a list. Here is the block of code for more clarity:
final List<FooBoo> fooboos = new ArrayList<>();
for (Foo foo : foos) {
Optional<Boo> boo = generateBoo(foo);
if (boo.isPresent()) {
fooboos.add(new FooBoo(foo, boo.get()));
}
}
I've tried something like this:
fooboos = foos
.stream()
.map(f -> generateBoo(f))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
But obviously I'm missing something here which is actuallying creating the FooBoo
object. How exactly do I do that with the java stream method?
fooboos = foos
.stream()
.map(foo -> generateBoo(foo).map(boo -> new FooBoo(foo, boo))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
Another possible answer is:
fooboos = foos.stream()
.flatMap(foo -> generateBoo(foo)
.map(boo -> new FooBoo(foo, boo))
.map(Stream::of)
.orElseGet(Stream::empty)
).collect(Collectors.toList());
I think in Java 9 we will see a stream
method added to Optional
. Then we will be able to do:
fooboos = foos.stream()
.flatMap(foo -> generateBoo(foo).map(boo -> new FooBoo(foo, boo)).stream())
.collect(Collectors.toList());
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