Java 8 Необязательная многоуровневая проверка нуля - PullRequest
0 голосов
/ 14 ноября 2018

Я работаю над программой, которая использует методы, которые возвращают Optional, и мне нужно перебрать ее и создать новый объект.Как мне это сделать?

import java.util.Optional;

class Info {
    String name;
    String profileId;

    Info(String name, String profileId) {
        this.name = name;
        this.profileId = profileId;
    }
}

class Profile {
    String profileId;
    String profileName;

    Profile(String profileId, String profileName) {
        this.profileId = profileId;
        this.profileName = profileName;
    }
}

class Content {
    String infoName;
    String profileName;

    Content(String infoName, String profileName) {
        this.infoName = infoName;
        this.profileName = profileName;
    }

    public java.lang.String toString() {
        return "Content{" + "infoName='" + infoName + '\'' + ", profileName='" + profileName + '\'' + '}';
    }
}

class InfoService {
    Optional<Info> findByName(String name){ //todo implementation }
}

class ProfileService {
   Optional<Profile> findById(String id) { //todo implementation }
}

class ContentService {

    Content createContent(Info i, Profile p) {
        return new Content(i.name, p.profileName);
    }

    Content createContent(Info i) {
        return new Content(i.name, null);
    }
}

public static void main(String[] args) {

    InfoService infoService = new InfoService();
    ProfileService profileService = new ProfileService();
    ContentService contentService = new ContentService();

    //setup
    Info i = new Info("info1", "p1");
    Profile p = new Profile("p1", "profile1");

    // TODO: the following part needs to be corrected
    Optional<Info> info = infoService.findByName("info1");

    if (!info.isPresent()) {
        return Optional.empty();
    } else {
         Optional<Profile> profile = profileService.findById(info.get().profileId);

         Content content;

         if (!profile.isPresent()) {
             content = contentService.createContent(info);
         } else {
             content = contentService.createContent(info, profile);
         }

        System.out.println(content);
     }
}

Мое понимание Java Optional заключается в сокращении проверок if null, но я все еще не могу сделать это без проверок if.Есть ли лучшее решение для использования map или flatMap и иметь краткий код?

1 Ответ

0 голосов
/ 14 ноября 2018

Это лучшее из того, что вы можете получить.map будет выполнять лямбду, только если она присутствует.orElseGet будет выполнять лямбду, только если это не так.

return infoService.findByName("info1")
    .map(info ->
        profileService.findById(info.profileId)
            .map(profile -> contentService.createContent(info, profile))
            .orElseGet(() -> contentService.createContent(info))
    );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...