我有以下代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
现在,pairValue可以为null.为了避免这里描述的NPE ,在"收集"时,我希望确保只发送那些非空的值.如果为null,我想发送"".
所以,我尝试用这个替换最后一行:
.collect(Collectors.toMap(Pair::getKey,Optional.ofNullable(Pair::getValue).orElse(""));
Run Code Online (Sandbox Code Playgroud)
以及其他修改:
.collect(Collectors.toMap(pair -> pair.getKey(), Optional.ofNullable(pair -> pair.getValue()).orElse(""));
Run Code Online (Sandbox Code Playgroud)
不编译.我不确定这里需要什么.有帮助吗?
在博客中看到这种代码驱使作者疯狂..为什么?
public boolean foo() {
boolean b = bar();
if (b == true) {
return true;
}
else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)