Java 8 stream adds a new object to the list from the return value

I want to save the return value of the method and use it to create a new object and add it to the list Here is a clearer block of code:

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 missed something here that is actually creating a fooboo object How do I do this using the Java streaming method?

Solution

fooboos = foos
fooboos = foos
        .stream()
        .map(foo -> generateBoo(foo).map(boo -> new FooBoo(foo,boo))
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>