您可以将内容收集到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);
}
顺便提一下,在返回类型中使用通配符是不被鼓励的,它们会使调用者的生活变得毫无必要的困难。
为了对比,这里是没有使用Stream进行相同操作的代码:
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));
}