[英]Simplifying if, else-if, else with Java optional
I have a method which takes in 3 parameters, all of which are optional.我有一个接受 3 个参数的方法,所有这些都是可选的。 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?有没有办法用 Optional.map.orElseGet 模式来简化这个? 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.
如果它只是 id,我可以想办法,但由于工作也是可选的,我不确定如何使用它。 Any advice to refactor this code would be much appreciated.
任何重构此代码的建议将不胜感激。
Create a builder object and use ifPresent
and assign the corresponding fields.创建一个构建器对象并使用
ifPresent
并分配相应的字段。
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
).正如迈克尔所建议的,您还可以用方法引用(
builder::withId
、 builder::withJobs
)替换 lambda 表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.