[英]Replace lambda expression with equivalent method in IntelliJ IDEA
Is there an Intellij IDEA refactoring that can replace a lambda expression with a function and function reference?是否有 Intellij IDEA 重构可以用函数和函数引用替换 lambda 表达式?
I have:我有:
List<String> convertToASlashBList(Collection<MyBean> beans) {
return beans.stream().map(bean -> "" + bean.getA() + "/" + bean.getB()).collect(toList());
}
I want:我想要:
List<String> convertToASlashBList(Collection<MyBean> beans) {
return beans.stream().map(this::convertToASlashB).collect(toList());
}
private String convertToASlashB(MyBean bean) {
return "" + bean.getA() + "/" + bean.getB();
}
There is the refactoring to extract an anonymous class but that is actually something different.有重构以提取匿名类,但这实际上是不同的。
You can do it in two steps:您可以分两步完成:
1. select the "" + bean.getA() + "/" + bean.getB()
part and press Cmd
+ Alt
+ M
(extract method). 1.选择
"" + bean.getA() + "/" + bean.getB()
部分,按Cmd
+ Alt
+ M
(提取方法)。 this will create your method and give you beans.stream().map(bean -> convertToASlashB(bean)).collect(toList())
.这将创建您的方法并为您提供
beans.stream().map(bean -> convertToASlashB(bean)).collect(toList())
。
2. right click on your lambda (it will be grayed) and do 'replace lambda with method reference' 2. 右键单击您的 lambda(它将变灰)并执行“用方法引用替换 lambda”
You can go to the line an press ALT+ENTER
, maybe they show options to replace this with other options (maybe changes functionality).您可以按
ALT+ENTER
转到该行,也许他们会显示选项以将其替换为其他选项(可能会更改功能)。
I don't know what you really need, but i've leave an example here.我不知道你真正需要什么,但我在这里留下了一个例子。
Example:例子:
List<String> convertToASlashBList(Collection<MyBean> beans) {
List<String> converted = new ArrayList<>();
for (MyBean bean : beans) {
converted.add(convertToASlashB(bean));
}
return converted;
}
private String convertToASlashB(MyBean bean) {
return "" + bean.getA() + "/" + bean.getB();
}
There are so many refactoring options in IntelliJ IDEA that it is not easy to find the correct one or even find the menu it resides in X) The hint from LinuxServers answer lead me in the right direction. IntelliJ IDEA 中有太多的重构选项,要找到正确的选项,甚至找到它所在的菜单都不容易 X) LinuxServers 答案中的提示将我引向了正确的方向。
There are two options:有两种选择:
ALT-ENTER
and select "Extract to method reference"ALT-ENTER
并选择“提取到方法引用”CTRL-ALT-M
) immediately followed by the quick fix ALT-ENTER
"Replace lambda with method reference"CTRL-ALT-M
),然后立即执行快速修复ALT-ENTER
“用方法引用替换 lambda”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.