1

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.

3 Answers 3

3

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'

Sign up to request clarification or add additional context in comments.

Comments

1

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();
}

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.