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?
Map<Foo,Boo>? If it's the latter, consider using Map.computeIfAbsent to populate the map on-the-fly.