我有这种方法可以从remittanceInformation
对象中提取一些信息
private static String combineStrings(RemittanceInformation remittanceInformation) {
return Optional.ofNullable(remittanceInformation)
.map(RemittanceInformation::getUstrds)
.map(l -> l.stream().collect(Collectors.joining(/* CRLF? */)))
.orElse(null);
}
现在remittanceInformation
内部的所有内容都是null
,这种情况下的方法应该返回null
但它返回带双引号的"null"
,为什么会这样?
字符串的连接会产生一个字符串,如果一个术语为null,则可能为“ null”(“” + null)。肯定是这种情况:一个非null的remittanceInformation,其中getUstrds()给出一个具有单个null的集合。
来自Optional.map()
Java文档
* If a value is present, apply the provided mapping function to it, * and if the result is non-null, return an {@code Optional} describing the * result. Otherwise return an empty {@code Optional}.
private static String combineStrings(RemittanceInformation remittanceInformation) {
return Optional.ofNullable(remittanceInformation)
.map(RemittanceInformation::getUstrds) // input is not null => apply mapping function return null => empty Optional
.map(l -> l.stream().collect(Collectors.joining(/* CRLF? */))) // input is not present, return an empty Optional
.orElse(null); // empty Optional so orElse return null;
}
如果打印出结果将是null