簡體   English   中英

Java流中的continue關鍵字的等價物?

[英]Equivalent of continue keyword in Java stream?

  for (final Prices ppr : prices) {
    if (!currency.getCode().equals(ppr.getCurrency().getCode())) {
      continue;
    }
    return ppr.getPrice();
  }

上面的代碼可以轉換成Java流代碼嗎? 我在使用continue關鍵字時遇到錯誤...

return prices.stream()
     .filter(ppr -> currency.getCode().equals(ppr.getCurrent().getCode()))
     .findFirst()
     .orElseThrow(NoSuchElementException::new);

只是為了擴展您提供的答案,您也可以這樣做

return prices.stream()
     .filter(ppr -> currency.getCode().equals(ppr.getCurrent().getCode()))
     .findFirst()
     .orElse(/* provide some default Price in case nothing is returned */);

而不是.findFirst()。get()返回不應該為空的值。 所以它假設會返回一些數據。 使用orElse語句,您可以提供默認值,以防返回任何內容。

暫無
暫無

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

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