I cannot do this in Java:
Optional optStr = Optional.of(\"foo\");
String result;
optStr.ifPresent(s -> result = s);
The doc sa
The answer is simple: you can't (directly) do that.
A very ugly hack would be to mutate an external object instead of assigning to a variable:
Optional optStr = Optional.of("foo");
StringBuilder sb = new StringBuilder();
optStr.ifPresent(s -> sb.append(s));
String result = sb.toString();
This works because sb
is effectively final here
But I want to emphasize the point that this is probably not what you really want to do.
optStr.orElse
or optStr.orElseGet
instead.optStr.map
Since you did not provide your whole use-case, these are just guesses but the key point is that I really do not recommend the above snippet of code: it goes against the concept of functional programming (by mutating an object).