【发布时间】:2018-11-14 13:03:46
【问题描述】:
我正在开发一个使用返回 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 并拥有简洁的代码?
【问题讨论】:
-
返回类型中存在
if else矛盾。 -
问题的简单性与您示例的复杂性不匹配。请改写(如果确实是一个复杂的问题)或将示例简化为 MCVE
-
@nullpointer 你能解释一下你的意思吗?这段代码是对我正在做的事情的重写(我不想使用公司代码库中使用的相同模型)
-
if (!info.isPresent()) { return Optional.empty(); }我的意思是这部分专门在 void 方法中,