简体   繁体   中英

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?

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). this will create your method and give you 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'

You can go to the line an press ALT+ENTER , maybe they show options to replace this with other options (maybe changes functionality).

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.

There are two options:

  1. Place cursor into lambda and hit ALT-ENTER and select "Extract to method reference"
  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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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