小编Yev*_*nov的帖子

从地图中删除值为空的所有条目

我想从地图中删除value为空的所有条目.看起来似乎并不复杂,但我试图找到一个更好的解决方案.


输入:

我有以下地图:

Map<String, Function<String, Optional<String>>> attributesToCalculate = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

其中key - 只是一个String和value - 对返回Optional <String>的方法的引用


输出:

结果,我想得到

Map<String, String> calculatedAttributes
Run Code Online (Sandbox Code Playgroud)

(不包括值为空的条目可选)


这是我的解决方案

      return attributesToCalculate.entrySet()
        .stream()
        .map(entry -> Pair.of(entry.getKey(), entry.getValue().apply(someString)))
        .filter(entry -> entry.getValue().isPresent())
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get()));
Run Code Online (Sandbox Code Playgroud)

但是我不喜欢.filter部分因为那时我必须在collect部分中的Optional上调用.get().

是否有更好的方法(可能没有.get调用)来解决这个问题?谢谢.

java collections optional java-stream

9
推荐指数
1
解决办法
1295
查看次数

标签 统计

collections ×1

java ×1

java-stream ×1

optional ×1