slartidan
slartidan

Reputation: 21586

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?

Upvotes: 8

Views: 7532

Answers (3)

Nathan van Dalen
Nathan van Dalen

Reputation: 23

First of all. IntelliJ IDEA will warn you to use Stream.of() Instead of Arrays#Stream, because you are not supplying an Array but just two Strings

After fixing that, just hit alt+enter standing in some place of x -> x+ "!" and press Extract to Method reference

But to be fair... if this tiny piece of code is the 'real deal' then please don't. It will make things less readable.

For this you are better of with something like:

System.out.println(String.join("!\n", new String[]{"a", "b"}));

or

Stream.of("a", "b").forEach(s -> System.out.printLn(s + "!"));

or even better:

for (String s : Arrays.asList("a", "b")) {
  System.out.println(s + "!");
}

Upvotes: 0

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

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

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140319

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

Upvotes: 26

Related Questions