我正在开发一个程序,该程序使用返回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
并使用简洁的代码?
答案 0 :(得分: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))
);