【问题标题】:Remove item from Stream with empty value从 Stream 中删除具有空值的项目
【发布时间】:2021-11-12 06:25:08
【问题描述】:

如何在我的流中删除具有空值的item.currencyDescription()

currencyService.getAllCurrencies().stream().collect(LinkedHashMap::new, (map, item) -> map.put(Integer.toString(item.currency()), item.currencyDescription()), Map::putAll));

【问题讨论】:

  • 您可以使用filterstream 来过滤集合
  • @Holger 是的!这就是目的
  • 所以,正如 pratap 所说,插入一个 filter,例如.filter(item -> !item.currencyDescription() .isEmpty()),在collect之前。

标签: java java-stream


【解决方案1】:

我相信这就是您在 cmets 中所建议的。

Map<String, String> result = list.stream()
                   .filter(item->!item.currencyDescription().isBlank())
                   .collect(LinkedHashMap::new,
                         (map, item) ->map.put(Integer.toString(item.currency()), 
                         item.currencyDescription()),
                         Map::putAll);

在您的情况下,它可能没有什么不同,但是通过使用收集器参数,您无法控制在重复的情况下将使用哪个item(您的方法采用最新的)。如果您想保留遇到的第一个重复项,可以这样做。

Map<String,String> result = list.stream().filter(item->!item.currencyDescription().isBlank())
        .collect(Collectors.toMap(item-> Integer.toString(item.currency()),
                   item->item.currencyDescription(),
                   (item1, item2)->item1,  // keep first duplicate
                   LinkedHashMap::new));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2022-08-13
    相关资源
    最近更新 更多