Java 8 Streams – 收集可能为null的值

我有以下代码
private static <T> Map<String,?> getDifference(final T a,final T b,final Map<String,Function<T,Object>> fields) {
    return fields.entrySet().stream()
            .map(e -> {
                final String name = e.getKey();
                final Function<T,Object> getter = e.getValue();
                final Object pairKey = getter.apply(a);
                final Object pairValue = getter.apply(b);
                if (Objects.equals(pairKey,pairValue)) {
                    return null;
                } else {
                    return Pair.of(name,pairValue);
                }
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(Pair::getKey,Pair::getValue));
    }

现在,pairValue可以为null.为了避免如here所述的NPE,在“收集”时,我希望确保只发送那些非空的值.如果为null,我想发送“”.

所以,我尝试用这个替换最后一行:

.collect(Collectors.toMap(Pair::getKey,Optional.ofNullable(Pair::getValue).orElse(""));

以及其他修改

.collect(Collectors.toMap(pair -> pair.getKey(),Optional.ofNullable(pair -> pair.getValue()).orElse(""));

不编译.我不确定这里需要什么.有帮助吗?

解决方法

你的语法不正确. toMap()的第二个参数必须是lambda,所以
.collect(Collectors.toMap(
             pair -> pair.getKey(),pair -> Optional.ofNullable(pair.getValue()).orElse("")
));

要么

你可以修改map()部分,如下所示

return Pair.of(name,Optional.ofNullable(pairValue).orElse(""));

并使用你的原始收藏()

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...