Java:在lambda中分配一个变量 [英] Java: Assign a variable within lambda

查看:315
本文介绍了Java:在lambda中分配一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能用Java做到这一点:

I cannot do this in Java:

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

文档说lambda中使用的变量必须是有效的。
然后如何很好地从lambda中提取和存储一些东西?

The doc says that the variables used in lambdas must be effectively final. Then how to extract and store something from a lambda into a variable nicely?

实际上真实的用例更复杂。

我想用 matcher.replaceAll 一个接一个地将几个正则表达式应用于字符串。我在forEach lambda中这样做,并希望在某处存储中间结果。

Actually the real use case is more complex.
I want to apply several regular expressions to a string one after another with matcher.replaceAll. I'm doing this in a forEach lambda and wanted to store intermediate results somewhere.

推荐答案

答案很简单:你可以' t(直接)这样做。

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<String> optStr = Optional.of("foo");
StringBuilder sb = new StringBuilder();
optStr.ifPresent(s -> sb.append(s));
String result = sb.toString();

这是有效的,因为 sb 有效最终

但我想强调一点,这可能不是你真正想做的事。

But I want to emphasize the point that this is probably not what you really want to do.


  • 如果您想拥有默认值,请改用 optStr.orElse optStr.orElseGet

  • 如果您想仅显示结果,请使用 optStr.map

  • 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).

这篇关于Java:在lambda中分配一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆