Your question: What is the difference between these methods? If they are different, which one is better and why?
After compilation, both will generate the same bytecode, but when writing this will give you more readability with a single-line implementation.
A great feature of Java 8 are Lambda expressions. With Lambda, you can write java code easier. The ugly look of the code has slightly changed with this function.
Example: Source
You can write Single Abstract Method (SAM) as lambda.
If your interface has only one method.
public interface StateChangeListener { public void onStateChange(State oldState, State newState); }
You can write it like a lambda, like this.
stateOwner.addStateListener( (oldState, newState) -> System.out.println("State changed") );
But both methods are the same, but you can see that the second one is so simple and remote from the ugly implementation.
In Kotlin, lambda expressions are different from Java.
Kotlin lambda expression example : source
val add: (Int, Int) -> Int = { a, b -> a + b }
The above function variable can be called as follows:
val addedValue: Int = add(5, 5)
This will return you the added value of two integers.
In this example, you can see (Int, Int) -> Int , this is called the lambda function in Kotlin.
So the lambda functions lambda lambda and lambda Java are completely different.
You can see in the Kotlin Docs:
Like Java 8, Kotlin supports SAM conversions. This means that Kotlin functional literals can be automatically converted to implement Java interfaces using one method other than the default, as long as the parameter types of the interface method match the parameter types of the Kotlin function.
Actually, you write lambda in kotlin, later it will be converted to a java interface. Thus, both methods are different. But when it comes to execution, they are both the same. This will not affect compilation time, so it has always been suggested to use lambda.
Hope this helps :)