收集可能为空的值

Collecting values that could be 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 可以为空。为了避免 here 所述的 NPE,在“收集”时,我希望确保只发送那些非空值。如果为空,我想发送“”。

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

.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(""));

并使用您原来的 collect()

您可以只收集到 HashMap 中,它允许 null 值而不需要 Optional:

private static <T> Map<String, Object> getDifference(
        final T a, final T b, final Map<String, Function<T, Object>> fields) {
    return fields.entrySet().stream()
        .map(e -> {
            final Function<T, Object> getter = e.getValue();
            final Object value = getter.apply(b);
            return Objects.equals(getter.apply(a),value)? null: Pair.of(e.getKey(), value);
        })
        .filter(Objects::nonNull)
        .collect(HashMap::new, (m,p) -> m.put(p.getKey(),p.getValue()), Map::putAll);
}

顺便说一句,不鼓励在 return 类型中使用通配符,它​​们会使调用者的生活不必要地变得困难,没有任何好处。

为了比较,这里没有流的相同操作:

private static <T> Map<String, Object> getDifference(
        final T a, final T b, final Map<String, Function<T, Object>> fields) {
    HashMap<String, Object> result = new HashMap<>();
    fields.forEach((key, getter) -> {
        final Object value = getter.apply(b);
        if(!Objects.equals(getter.apply(a), value)) result.put(key, value);
    });
    return result;
}

当然,这也适用于可选的:

private static <T> Map<String, Optional<Object>> getDifference(
        final T a, final T b, final Map<String, Function<T, Object>> fields) {
    HashMap<String, Optional<Object>> result = new HashMap<>();
    fields.forEach((key, getter) -> {
        final Object value = getter.apply(b);
        if(!Objects.equals(getter.apply(a), value))
            result.put(key, Optional.ofNullable(value));
    });
    return result;
}

但是如果您只想用空字符串替换 null,则不需要 Optional:

private static <T> Map<String, Object> getDifference(
        final T a, final T b, final Map<String, Function<T, Object>> fields) {
    HashMap<String, Object> result = new HashMap<>();
    fields.forEach((key,getter) -> {
            final Object value = getter.apply(b);
            if(!Objects.equals(getter.apply(a), value))
                result.put(key, value==null? "": value);
        });
    return result;
}

好吧,如果您只是在 map 函数而不是收集器中执行此替换,那么此替换也可以立即使用您的原始代码:

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==null? "": pairValue);
            }
        })
        .filter(Objects::nonNull)
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}

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