简体   繁体   English

用 IntelliJ IDEA 中的等效方法替换 lambda 表达式

[英]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:有两种选择:

  1. Place cursor into lambda and hit ALT-ENTER and select "Extract to method reference"将光标置于 lambda 中并按ALT-ENTER并选择“提取到方法引用”
  2. Select the lambda body and execute refactoring "Extract Method" (from Main Menu or from Refactor This Menu or CTRL-ALT-M ) immediately followed by the quick fix ALT-ENTER "Replace lambda with method reference"选择 lambda 主体并立即执行重构“提取方法”(从主菜单或重构此菜单或CTRL-ALT-M ),然后立即执行快速修复ALT-ENTER “用方法引用替换 lambda”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM