Java: Assign a variable within lambda

前端 未结 4 1849
忘了有多久
忘了有多久 2021-02-08 03:22

I cannot do this in Java:

Optional optStr = Optional.of(\"foo\");
String result;
optStr.ifPresent(s -> result = s);

The doc sa

4条回答
  •  你的背包
    2021-02-08 04:05

    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.

    • If you want to have a default value, use optStr.orElse or optStr.orElseGet instead.
    • If you want to map the result only if it is present, use 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).

提交回复
热议问题