Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream add new object to list from return value

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?

like image 591
Richard Avatar asked Sep 17 '25 21:09

Richard


2 Answers

fooboos = foos
        .stream()
        .map(foo -> generateBoo(foo).map(boo -> new FooBoo(foo, boo))
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());
like image 100
JB Nizet Avatar answered Sep 19 '25 09:09

JB Nizet


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());
like image 29
3 revsPaul Boddington Avatar answered Sep 19 '25 10:09

3 revsPaul Boddington