Vavr: Howto flatmap collection inside optional object

Viewed 2265

Is any easiest way to write this code below, without using toStream()?

import io.vavr.collection.List;
import io.vavr.control.Option;
import lombok.Value;

public class VavrDemo {

    public static void main(String[] args) {
        Foo bar = new Foo(List.of(new Bar(1), new Bar(2)));
        Number value = Option.some(bar)
                .toStream()              // <- WTF?!?
                .flatMap(Foo::getBars)
                .map(Bar::getValue)
                .sum();
        System.out.println(value);
    }

    @Value
    static class Foo {
        private List<Bar> bars;
    }

    @Value
    static class Bar {
        private int value;
    }
}
2 Answers

How about using .fold() or .getOrElse()?

Option.some(bar)
    .fold(List::<Bar>empty, Foo::getBars)
    .map(Bar::getValue)
    .sum();
Option.some(bar)
    .map(Foo::getBars)
    .getOrElse(List::empty)
    .map(Bar::getValue)
    .sum();
Related