从具有空值的 Stream 中删除项目

Remove item from Stream with empty value

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

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

我相信这就是您在评论中所建议的内容。

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));