用空字符串装饰器替换 null
Replace null with empty String decorator
Cactoos 框架中是否有一些文本装饰器(或其他方式),可以用空字符串替换空字符串?就像 Google Guava 中的 Strings.nullToEmpty 函数。
我找到了 NoNulls 装饰器,但我只需要替换而不抛出异常。
所以它必须是这样的:
String someNullString = null;
new StrictEmptyText(
new TextOf(someNullString) // this row produces NPE for now
).asString(); // ""
非常感谢您的帮助。
您可以像这样使用 Java 8 中的 Optional::ofNullable
:
String str = Optional.ofNullable(someNullString)
.orElse(""); // return empty if someNullString is null or someNullString if not null
不,没有 Text
实现可以直接为您执行此操作。
使用纯仙人掌:
new TextOf(
new UncheckedScalar<>(
new Ternary<>(
someNullString != null,
someNullString,
""
)
).value()
)
Cactoos 框架中是否有一些文本装饰器(或其他方式),可以用空字符串替换空字符串?就像 Google Guava 中的 Strings.nullToEmpty 函数。
我找到了 NoNulls 装饰器,但我只需要替换而不抛出异常。
所以它必须是这样的:
String someNullString = null;
new StrictEmptyText(
new TextOf(someNullString) // this row produces NPE for now
).asString(); // ""
非常感谢您的帮助。
您可以像这样使用 Java 8 中的 Optional::ofNullable
:
String str = Optional.ofNullable(someNullString)
.orElse(""); // return empty if someNullString is null or someNullString if not null
不,没有 Text
实现可以直接为您执行此操作。
使用纯仙人掌:
new TextOf(
new UncheckedScalar<>(
new Ternary<>(
someNullString != null,
someNullString,
""
)
).value()
)