Java – Replace null with an empty string decorator

Replace null with an empty string decorator… here is a solution to the problem.

Replace null with an empty string decorator

Are there some text decorators in the Cactoos framework (or some other way) that can replace empty strings with empty strings? Similar to the Strings.nullToEmpty function in Google Guava.

I

found the NoNulls decorator, but I just need to replace without throwing an exception.

So it must be like this:

String someNullString = null; 
new StrictEmptyText(
 new TextOf(someNullString) // this row produces NPE for now
).asString(); // ""

Thank you very much for your help.

Solution

No, there is no Text implementation that can do this for you directly.

Use pure cactus:

new TextOf(
  new UncheckedScalar<>(
    new Ternary<>(
      someNullString != null,
      someNullString,
      ""
    )
  ).value()
)

Related Problems and Solutions