Search code examples
javafunctional-programmingcoding-styleoption-type

What is the idiomatic "functional" way to take an Optional<String> and return a default string if null or empty, a modified string otherwise?


What is the idiomatic, minimal (perhaps functional?) way to take an Optional<String> and say,

  • return a default string, e.g. true if null or empty, or
  • return a modified string, e.g. query_str = <str> otherwise.

Of course, there's my clunky attempt:

Optional<String> queryMaybe; // Given.
String clause = "true";
if (queryMaybe.isPresent() && !queryMaybe.get().isEmpty()) {
  clause = "query_str = " + queryMaybe.get();
}

But the surrounding code written by my colleagues seems to use a lot of, what I think might be called, "functional" style—chaining. For example,

String externalTraffickedStateClauses = StringUtils.defaultIfBlank(
    externalTraffickedStateQueries.stream().collect(Collectors.joining(" OR ")), "false");

and

SORTORDERBY orderBy = orderByMaybe.orElse(DEFAULT_ORDER_BY);

So, I'm trying to conform to their style as much as I can, i.e. chain stream, filter, orElse, etc. Not sure if it's because I'm coming from a C++ background or because my learnings are simply outdated, but this is still very unfamiliar to me.


Solution

  • Does this do what you're looking for?

    return queryMaybe
        .filter(query -> !query.isEmpty())
        .map(query -> "query_str = " + query)
        .orElse("true")