r/learnjava • • Mar 30 '20

Java Lambda expressions

I am a little lost as to what they are, how they work or what I can use them for.

I have no real example, just stumbled across the term and would like to understand it.

Are there understandable easy examples?

Thanks for possible help.

Edit: I found a pretty good explanation here. I just needed a easy and small example to wrap my head around this. Thanks to everyone who tried to help.

41 Upvotes

7 comments sorted by

View all comments

3

u/AnotherThrowAway_9 Mar 30 '20

If you have a functional interface you can use a lambda. Lambdas reduce the amount of code that you have to write.

Thread t = new Thread( () -> { myObject.func() } );

That’s much shorter than writing the code into the runnable() method.

You can also do this with actionlisteners for the actionPerformed() method.

So you can use them in places when you write “implements AnInterfaceHere”

2

u/BananaPunsch Mar 30 '20

In other words: I can use a Lambda, if I have a interface class with only one method. And with using the Lambda I can use that method in classes that implement the interface without having to overwrite the method. Is that basically it, or am I missing the point?