is it possible to use twice ifPresent each one checking different return or bifurcate map

北慕城南 提交于 2019-12-06 05:27:07

You can catch your result like that:

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
    .map(CodeOndernemingOfVestigingType::getValue) 
    .map(o -> {
        myMethod("onderneming_type", o.getValue());
        return o.getBeschrijving();
    })
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

Take a notice, that multiline lambdas are bad and hard to read, so you can extract it into private method.

EDIT You want to branch your Optional. Is not possible and you should do:

Optional<Code> op = Optional.ofNullable(onderneming.getOndernemingOfVestiging())
    .map(OndernemingOfVestigingType::getCode) 

op.map(CodeOndernemingOfVestigingType::getValue)
    .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

op.map(CodeOndernemingOfVestigingType::getBeschrijving) 
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

It should be more readable than do some hacks.

I've a bit simplified your example here if u don't mind and here is what I came up with:

static class User {

    private final Integer age;

    private final String name;

    public User(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Optional<Integer> getAge() {
        return Optional.ofNullable(age);
    }

    public String getName() {
        return name;
    }
}

And then :

    Optional<User> user = Optional.of(new User(null, "test"));

    user.map(u -> Map.entry(u, u.getAge())) // this is java-9 Map.entry; but you can use a Pair or a List/array etc
            .ifPresent(x -> {
                System.out.println("name = " + x.getKey().getName());
                x.getValue().ifPresent(age -> {
                    System.out.println("age = " + age);
                });
            });

You could apply the same thing to your input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!