Java 8 streams – collect potentially null values

I have the following code:

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 can now be null In order to avoid NPE as described here, I want to ensure that only those non empty values are sent during "collection" If NULL, I want to send ""

So I try to replace the last line with this:

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

And other modifications:

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

Do not compile I'm not sure what I need here Does it help?

Solution

Your grammar is incorrect The second parameter of tomap () must be lambda, so

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

or

You can modify the map () section as follows

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

And use your original collection ()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>