簡體   English   中英

流連接結果默認值

[英]Stream join result default value

如果我通過流加入幾個字符串並且沒有任何內容可以加入結果,那么就是一個像“”這樣的空字符串。 是否有可能在它為空時添加默認值? 例如“ - ”

someList.stream()
                .filter(a -> a.getKey() != null)
                .map(a -> a.getKey())
                .sorted()
                .collect(Collectors.joining(", ")); 

更新:我知道還有其他方法可以做到但我只是想知道是否可以覆蓋默認值“”(空字符串)

String result = someList.stream()
        .filter(a -> a.getKey() != null)
        .map(a -> a.getKey())
        .sorted()
        .reduce((a,b) -> a + ", " + b).orElse("-");

我們在哪里使用reduce而不是collect。

編輯:第一個解決方案確實沒有按預期工作。 這個是。

為什么不添加像if (outString.isEmpty()) return "-";

就在你的代碼之后

String outString = someList.stream()
            .filter(a -> a.getKey() != null)
            .map(a -> a.getKey())
            .sorted()
            .collect(Collectors.joining(", ")); 

if (outString.isEmpty()) 
   return "-";
else 
   return outString;

暫無
暫無

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

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