英文:
Simplifying if, else-if, else with Java optional
问题
我有一个方法,接受三个参数,全部都是可选的。方法的实现如下。
public static Person getPerson(Optional<String> id, Optional<List> jobs, Optional<String> country) {
Person p = null;
if(id.isPresent() && jobs.isPresent()) {
p = Person.builder.withName("Name").withId(id.get()).withJobs(jobs.get()).build();
} else if (id.isPresent()) {
p = Person.builder.withName("Name").withId(id.get()).build();
} else {
p = Person.builder.withName("Name").build();
}
return p;
}
是否有办法使用Optional.map.orElseGet模式来简化这个代码?如果只有id,我可以想出一种方法,但由于jobs也是可选的,我不太确定该如何使用它。非常感谢您提供重构此代码的任何建议。
英文:
I have a method which takes in 3 parameters, all of which are optional. Implementation of the method is as follows.
public static Person getPerson(Optional<String> id, Optional<List> jobs, Optional<String> country) {
Person p = null;
if(id.isPresent() && jobs.isPresent()) {
p = Person.builder.withName("Name").withId(id.get()).withJobs(jobs.get()).build();
} else if (id.isPresent()) {
p = Person.builder.withName("Name").withId(id.get()).build();
} else {
p = Person.builder.withName("Name").build();
}
return p;
}
Is there a way to simplify this with Optional.map.orElseGet pattern? If its just the id I could think of a way, but since jobs is also optional I'm not sure how I could use that. Any advice to refactor this code would be much appreciated.
答案1
得分: 4
创建一个构建器对象,使用 ifPresent
方法并赋值相应的字段。
PersonBuilder builder = Person.builder.withName("Name");
id.ifPresent(idValue -> builder.withId(idValue));
jobs.ifPresent(jobsValue -> builder.withJobs(jobsValue));
return builder.build();
正如Michael建议的那样,你还可以用方法引用来替换lambda表达式(builder::withId
,builder::withJobs
)。
英文:
Create a builder object and use ifPresent
and assign the corresponding fields.
PersonBuilder builder = Person.builder.withName("Name");
id.ifPresent(idValue -> builder.withId(idValue));
jobs.ifPresent(jobsValue -> builder.withJobs(jobsValue));
return builder.build();
As Michael suggests, you can also replace the lambda expression with a method reference (builder::withId
, builder::withJobs
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论