Andrew Cheong
Andrew Cheong

Reputation: 30293

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,

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.

Upvotes: 1

Views: 360

Answers (1)

Malcolm Crum
Malcolm Crum

Reputation: 4879

Does this do what you're looking for?

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

Upvotes: 5

Related Questions