简化Java中的if、else-if、else结构使用Optional:

huangapple go评论77阅读模式
英文:

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&lt;String&gt; id, Optional&lt;List&gt; jobs, Optional&lt;String&gt; country) {
    Person p = null;
 
    if(id.isPresent() &amp;&amp; jobs.isPresent()) {
      p = Person.builder.withName(&quot;Name&quot;).withId(id.get()).withJobs(jobs.get()).build();
    } else if (id.isPresent()) {
       p = Person.builder.withName(&quot;Name&quot;).withId(id.get()).build();
    } else {
       p = Person.builder.withName(&quot;Name&quot;).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::withIdbuilder::withJobs)。

英文:

Create a builder object and use ifPresent and assign the corresponding fields.

PersonBuilder builder = Person.builder.withName(&quot;Name&quot;);

id.ifPresent(idValue -&gt; builder.withId(idValue));
jobs.ifPresent(jobsValue -&gt; builder.withJobs(jobsValue));

return builder.build();

As Michael suggests, you can also replace the lambda expression with a method reference (builder::withId, builder::withJobs).

huangapple
  • 本文由 发表于 2020年9月26日 02:21:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64069477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定