58

I have the following anonymous Runnable implementation.

Runnable cronTask = new Runnable() {
       @Override
       public void run() {
          // do something
       }
};

IntelliJ suggests that I replace it with a lambda expression. eg:

Runnable cronTask = () -> {
     // multiple "do something" statements
};

When using a single statement the syntax is:

Runnable cronTask = () -> doSomething();

What shortcut can I use to convert it?

Technotronic
  • 8,424
  • 4
  • 40
  • 53
  • 7
    `Runnable task = () -> doSomething();` or `Runnable task = () -> { multiple(); statetements(); };` – assylias Dec 02 '15 at 16:57
  • @Makoto [Good try!](http://meta.stackexchange.com/questions/132923/can-i-place-kbd-kbd-in-a-comment) ;-) – assylias Dec 02 '15 at 16:58

2 Answers2

114

Let IntelliJ do the lifting here; you can invoke Alt + Enter (or Option + Return on Mac) to allow IntelliJ to replace it with a lambda expression.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 7
    The only question left is why doesn’t it provide this option when hovering the mouse over the suggestion, as with most of the other code improvement suggestions (if it did, we had a consistent behavior across all Java 8 enabled IDEs)… – Holger Dec 02 '15 at 18:00
  • Old post, but where do you hold the cursor? if i press option + return . i simply break the current line. – Gillis Haasnoot May 23 '18 at 22:15
  • 1
    @GillisHaasnoot: The visual cue is usually available right there; wherever the squiggly yellow line appears is a good spot to place the cursor before invoking the above. – Makoto May 23 '18 at 22:31
  • Yes found it. Little bulb icon appears when you hover over the affected words. – Gillis Haasnoot May 23 '18 at 22:40
  • thanks a lot, this is quick action to replace the lambda inspection – mochadwi Jan 03 '20 at 11:00
  • Is there a shortcut to just start a lambda when writing code the first time? – Literate Corvette Oct 23 '20 at 05:06
25

Alt + Enter is good way to change each one individual

but there is away to change all lambda expression across app

Run Inspection by Name

Ctrl + Shift+ Alt + I

source site

How we can use it in our Android Studio and lambda expression:

just write replace lambda as Inspection name called anonymous type can be replaced with lambda

List of occurrence will appear change each one manually

Tutorial Video

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156