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

Yev*_*nov 9 java collections optional java-stream

我想从地图中删除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调用)来解决这个问题?谢谢.

Pau*_*ton 12

如上所述,get如果您已经检查过Optional非空,则使用没有任何问题.

但是,我认为这段代码最好不使用流表达.

Map<String, String> result = new HashMap<>();
attributesToCalculate.forEach((k, v) ->
    v.apply(someString).ifPresent(str -> result.put(k, str))
);
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢forEach以这种方式使用填充地图,则可以使用简单的for循环.