Java 8 Streams - Collecting Values that could be null

user2116243 :

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

Now, pairValue can be null. In order to avoid the NPE as described here, while "collect"ing, I wish to ensure that I send only those values that are non-null. If null, I want to send "".

So, I tried replacing the last line with this:

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

And other modifications thereof:

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

Does not compile. I'm not sure what is needed here. Any help?

Nikolai Shevchenko :

You have incorrect syntax. toMap()'s second parameter must be lambda, so

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

OR

you can modify map() section as follows

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

and use your original collect()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465842&siteId=1