What is the idiomatic, minimal (perhaps functional?) way to take an Optional<String>
and say,
true
if null or empty, orquery_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.
Does this do what you're looking for?
return queryMaybe
.filter(query -> !query.isEmpty())
.map(query -> "query_str = " + query)
.orElse("true")