简体   繁体   中英

How to port from java.util.Optional method call chaining to Guava Optional?

I have the following that uses java.util.optional

// this works fine for java.util.Optional
Optional <Context> xx = Optional.ofNullable(x);
Optional<DateRange> dates = xx.map(Context::getEntity).map(Entitiy::getDates);

However, I need to convert that to use guava's optional. I tried something like guava Optional transform but I'm unsure how to chain something like this with guava optional?

// guava...how can I chain method calls as such...this fails of course
Optional <Context> xx = Optional.of(x);
Optional<DateRange> dates = xx.get().getEntity().getDates();

Any help is greatly appreciated!

It will be almost exactly the same. Just methods' name are different, but usage is exactly the same.

Just keep in mind that Guava's Optional.of() and Java8's Optional.ofNullable() are not the same. You should use Guava's Optional.fromNullable() instead.

Guava's Optional.transform() is equal to Java8's Optional.map() .

Optional<Context> xx = Optional.fromNullable(x);
Optional<DateRange> dates = xx.transform(Context::getEntity).transform(Entitiy::getDates);

If you are not using Java8, you won't be able to use lambdas and method references, so you will have to go on with anonymous classes implementing Function interface:

xx.transform(new Function<Context, Entity>() {
        @Override
        public Entity apply(Context c) {
            return c.getEntity();
        }
    })

and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM