簡體   English   中英

Java null 使用 Optionals 檢查多個屬性

[英]Java null check on multiple properties with Optionals

從 java 11 到 null 檢查同一個 object 的多個字段的最有效方法是什么? 我正在使用可選項,但我不明白如何將它們與相同 object 的更多字段一起使用

    Map<String, NestedQuery> nested = new HashMap<>();
    if (getSentDate() != null) {
      if (getSentDate().getFrom() != null && getSentDate().getTo() != null) {
        nested.put(...); 
      }
    }
    return nested;

在我的例子中, getSentdate()返回一個 object,它有getFrom()getTo() ,它們的值可能是也可能不是 null

我嘗試過這個但是在 if 子句中使用 of.ifPresent 是一個很大的不

    Map<String, NestedQuery> nested = new HashMap<>();
    Optional.ofNullable(getSentDate())
        .ifPresent(sentDate -> {
          Optional<String> from = Optional.ofNullable(sentDate.getFrom());
          Optional<String> to = Optional.ofNullable(sentDate.getTo());
          if(from.isPresent() && to.isPresent()){
            nested.put(...);
          }
        });
    return nested;

正如上面評論中所說,您的原始代碼實際上非常有效(我們可能需要一些有效性標准):

if (getSentDate() != null) {
      if (getSentDate().getFrom() != null && getSentDate().getTo() != null) {

但是,如果你真的想使用Optional來消除一些null 檢查,那么只使用一個就足夠了:

Optional.ofNullable(getSentDate())
        .filter(sentDate -> Objects.nonNull(sentDate.getFrom()))
        .filter(sentDate -> Objects.nonNull(sentDate.getTo())) 
        .ifPresent(date -> nested.put(...)); 

在這種情況下.ifPresent(date -> nested.put(...))僅在滿足所有 3 個條件時執行: getSentDate()不是nullsentDate.getFrom()不是null並且sentDate.getTo()是也不null 然而,我們仍然有一個 null 檢查,我們正在“濫用” Objects#nonNull方法,因為:

API 注意:此方法的存在是為了用作謂詞,filter(Objects::nonNull)

這相當於

Optional.ofNullable(getSentDate())
        .filter(sentDate -> sentDate.getFrom() != null)
        .filter(sentDate -> sentDate.getTo() != null) 
        .ifPresent(date -> nested.put(...)); 

另請注意,這實際上“違反”了可選用法

API 注意:Optional 主要用作方法返回類型,其中明確需要表示“無結果”,並且使用 null 可能會導致錯誤。

嘗試以下操作,這里 NestedQuery 有一個可選的發送日期,而 SendDate 有可選的 getFrom 和 getTo 值。 您可以使用 ifpresent ans ispresent 檢查該值是否存在

private interface SendDate {

Optional<Object> getFrom();

Optional<Object> getTo();
}

private interface NestedQuery {

public Optional<SendDate> getSendDate();
}

private static NestedQuery createNestedQuery() {
return Optional::empty;
}

public static void main(final String[] args) {
final Map<String, NestedQuery> nested = new HashMap<>();
final NestedQuery nestedQuery = createNestedQuery();
nestedQuery.getSendDate().ifPresent(sendDate -> {
    if (sendDate.getFrom().isPresent() && sendDate.getTo().isPresent())
    nested.put("", nestedQuery);
});
System.out.println(nested.toString());
}

盡管使用 && 的條件表達式及其短路行為是您在處理多級屬性時可以獲得的最佳結果。 不過,對於單層嵌套,您可以輕松引入一個實用程序,它不符合 null 中的任何屬性。

@SafeVarargs
static <T> boolean noneNull(T... args) {
    return Arrays.stream(args).noneMatch(Objects::isNull);
}

並將其用作

if(noneNull(sentDate.getFrom(), sentDate.getTo())) {
    nested.put(...)
}

請注意,這里不涉及Optional ,通常不需要檢查 null 對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM