为什么此方法返回“ null”但不为null

问题描述 投票:0回答:2

我有这种方法可以从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",为什么会这样?

java stream
2个回答
2
投票

字符串的连接会产生一个字符串,如果一个术语为null,则可能为“ null”(“” + null)。肯定是这种情况:一个非null的remittanceInformation,其中getUstrds()给出一个具有单个null的集合。


0
投票

来自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

© www.soinside.com 2019 - 2024. All rights reserved.