Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor a lambda expression to a method reference?

My code looks like this:

class A {
    public void m() {
        Arrays.stream("a", "b")
            .map(x -> x + "!") // <-- lambda expression
            .forEachOrdered(System.out::println);
    }
}

I want to refactor it into:

class A {
    public void m() {
        Arrays.stream("a", "b")
            .map(this::t) // <-- method reference
            .forEachOrdered(System.out::println);
    }

    public String t(String x) {
        return x + "!";
    }
}

How can I do this refactoring with IntelliJ?

like image 350
slartidan Avatar asked Jan 26 '18 09:01

slartidan


Video Answer


2 Answers

Select the lambda, press Alt+Enter, click "Extract to Method Reference".

like image 92
Andy Turner Avatar answered Oct 14 '22 12:10

Andy Turner


First, do the refactoring extract method on x + "!" code. Then use quick-fix replace with method reference.

like image 40
Sergii Lagutin Avatar answered Oct 14 '22 12:10

Sergii Lagutin