我有以下代码:
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。为了避免所描述的NPE 这里,而“收集” ING,我想确保我只发送那些非空值。如果为null,我想送“”。
所以,我想这个替换最后一行:
.collect(Collectors.toMap(Pair::getKey,Optional.ofNullable(Pair::getValue).orElse(""));
和其他修饰物:
.collect(Collectors.toMap(pair -> pair.getKey(), Optional.ofNullable(pair -> pair.getValue()).orElse(""));
不能编译。我不知道这里需要什么。任何帮助吗?
你有不正确的语法。toMap()
的第二个参数必须是拉姆达,所以
.collect(Collectors.toMap(
pair -> pair.getKey(),
pair -> Optional.ofNullable(pair.getValue()).orElse("")
));
要么
您可以修改map()
如下节
return Pair.of(name, Optional.ofNullable(pairValue).orElse(""));
并使用你原来的 collect()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句