Java 8可选的多级空检查

bin*_*iam 1 java null optional java-8

我正在开发一个程序,它使用返回的方法,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);
     }
}
Run Code Online (Sandbox Code Playgroud)

我对Java Optional的理解是减少if null检查,但如果没有检查我仍然无法做到if.有没有更好的解决方案使用mapflatMap具有简洁的代码?

Mic*_*ael 8

这是你能得到的最好的.map如果它存在,将只执行lambda.orElseGet如果不是,它将只执行lambda.

return infoService.findByName("info1")
    .map(info ->
        profileService.findById(info.profileId)
            .map(profile -> contentService.createContent(info, profile))
            .orElseGet(() -> contentService.createContent(info))
    );
Run Code Online (Sandbox Code Playgroud)