簡體   English   中英

如何在沒有return語句的情況下編寫此lambda表達式?

[英]How I can write this lambda expression without a return statement?

以下方法實現了一個BiFunction ,該BiFunction采用Map<String,String>和要搜索的值。 它在包含給定值的Map中搜索一個Entry ,並返回相應的鍵。

此實現有效,但我想編寫不帶return語句的lambda表達式,以使代碼更優雅。

private BiFunction<Map<String, String>, String, String> findName = (m, s) -> {
    Map.Entry<String, String> e = 
        m.entrySet()
         .stream()
         .filter(entry -> entry.getValue() != null && !entry.getValue().isEmpty() && entry.getValue().equals(s))
         .findFirst()
         .orElse(null);
    return e != null ? e.getKey() : null;
};

我該怎么做?

為了擺脫return語句和花括號,lambda表達式的主體必須是單個表達式,其類型是lambda表達式的返回類型-在您的情況下為String

您的findFirst()返回Optional<Map.Entry<String,String>> 您希望將其映射到Optional<String> (其中String是條目的鍵),如果為空,則返回null

您可以使用Optionalmap方法來實現:

private BiFunction<Map<String, String>, String, String> findName = (m, s) -> 
    m.entrySet().stream()
            .filter(entry -> entry.getValue() != null && !entry.getValue().isEmpty() && entry.getValue().equals(s))
            .findFirst()
            .map(Map.Entry::getKey)
            .orElse(null);

暫無
暫無

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

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