检查Optional中是否存在空属性并返回String的Java Stream API代码。

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

Check if null attribute present in Optional and return String Java Stream API

问题

我有以下内容:

class Person
  private String firstName;
  private String familyName;

  // 设置器和获取器

我有以下方法:

public String getFullName(Optional<Person> persons) {
  return persons
           .map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("无效");
}

我只想检查名字或姓氏是否为null,如果是,则显示“无效”该人。我在考虑添加一个验证方法,但我确定有一种更简单的方法,我想不出来。

英文:

I have the following

class Person
  private String firstName;
  private String familyName;

  // Setters and Getters

And I have the following method

public String getFullName(Optional&lt;Person&gt; persons) {
  return persons
           .map(person -&gt; (person.getFirstName() + &quot; &quot; + person.getFamilyName())).orElse(&quot;Invalid&quot;);
}

I just want to check if either first or last name is null, display &quot;Invalid&quot; for that person. I was thinking to add a method for validation but I am sure there is an easier way I cannot think about.

答案1

得分: 4

你正在查看 [Optional::filter][1],在 map 之前:

return persons
        .filter(person -> person.getFamilyName() != null && person.getFirstName() != null)
        .map(person -> person.getFirstName() + " " + person.getFamilyName())
        .orElse("无效");

这意味着如果姓氏和名字不为 null则创建连接否则返回无效消息或者您甚至可以使用 `orElseThrow` 抛出异常
  [1]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-
英文:

You are looking to [Optional::filter][1], before the map:

return persons
        .filter(person -&gt; person.getFamilyName() != null &amp;&amp; person.getFirstName() != null)
        .map(person -&gt; person.getFirstName() + &quot; &quot; + person.getFamilyName())
        .orElse(&quot;Invalid&quot;);

Which mean, if the family and first names are not null then create your concatination, otherwise return an Invalid message, or you can even throw an exception by using orElseThrow
[1]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-

答案2

得分: 1

你可以使用filter来实现:

public String getFullName(Optional<Person> persons) {
  return persons
           .filter(person -> Objects.nonNull(person.getFirstName()) && Objects.nonNull(person.getFamilyName()))
           .map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid");
}
英文:

You can use filter for that:

public String getFullName(Optional&lt;Person&gt; persons) {
  return persons
           .filter(person -&gt; Objects.nonNull(person.getFirstName()) &amp;&amp; Objects.nonNull(person.getFamilyName()))
           .map(person -&gt; (person.getFirstName() + &quot; &quot; + person.getFamilyName())).orElse(&quot;Invalid&quot;);
}

答案3

得分: 1

另一种函数式方法。

首先,为了进行必填字段验证,创建一个谓词构建器方法:

public static <T, F> Predicate<T> hasRequiredValue(Function<T, F> fieldGetter) {
    return fieldGetter.andThen(Objects::nonNull)::apply;
}

然后稍微修改 getFullName 方法:

public Optional<String> getFullName(Person person) {
    return Optional.ofNullable(person)
                   .filter(hasRequiredValue(Person::getFamilyName))
                   .filter(hasRequiredValue(Person::getFirstName))
                   .map(p -> p.getFirstName() + " " + p.getFamilyName());
}

然后按以下方式使用:

Person person = ...
String fullName = getFullName(person).orElse("Invalid");
英文:

Another functional approach.

First create a predicate builder method for required field validation:

public static &lt;T, F&gt; Predicate&lt;T&gt; hasRequiredValue(Function&lt;T, F&gt; fieldGetter) {
    return fieldGetter.andThen(Objects::nonNull)::apply;
}

And modify the getFullName a little bit:

public Optional&lt;String&gt; getFullName(Person person) {
    return Optional.ofNullable(person)
                   .filter(hasRequiredValue(Person::getFamilyName))
                   .filter(hasRequiredValue(Person::getFirstName))
                   .map(p -&gt; p.getFirstName() + &quot; &quot; + p.getFamilyName());
}

Then use it as follows:

Person person = ...
String fullName = getFullName(person).orElse(&quot;Invalid&quot;);

huangapple
  • 本文由 发表于 2020年4月4日 00:50:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61016694.html
匿名

发表评论

匿名网友

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

确定