You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java Stream中移除item.currencyDescription为空的元素

你可以在collect终止操作之前增加filter中间操作,过滤掉currencyDescription()返回值为空的元素即可。

修改后代码如下:

currencyService.getAllCurrencies().stream()
    // 过滤currencyDescription为null、空字符串、全空白的项
    .filter(item -> item.currencyDescription() != null && !item.currencyDescription().isBlank())
    .collect(LinkedHashMap::new, 
            (map, item) -> map.put(Integer.toString(item.currency()), item.currencyDescription()), 
            Map::putAll);

补充说明:

  • 如果你仅需要排除null值,可将filter条件简化为item -> item.currencyDescription() != null
  • 如果你使用的是Java 11以下版本,没有内置isBlank()方法,可以替换为!item.currencyDescription().trim().isEmpty(),同样可以实现排除空字符串和全空白内容的效果

内容的提问来源于stack exchange,提问作者Joerdan Devera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:36:06