Take this simple piece of code
new Thread(() -> {
}).start();
I know it works, but how do I write my own class to allow someone to use it in the same manner?
Take this simple piece of code
new Thread(() -> {
}).start();
I know it works, but how do I write my own class to allow someone to use it in the same manner?
Lambda works on Functional Interfaces, so if your class or method have ability to take such interface as parameter then you can use your class/method that manner.
new Thread(() -> {
}).start();
This code works as Thread
has a overloaded constructor which take functional interface Runnable
as arguments.
Example: How to write own class
Here DoWork
is our functional Interface which has only abstract method doit
public interface DoWork {
public void doit(String str);
}
Let we have a class named MyClass
whose constructor take DoWork
as arguments and have a method startWork
to start the work(Ordinary Method).
public class MyClass {
DoWork dw;
public MyClass(DoWork dw) {
this.dw = dw;
}
public void startWork(String s){
dw.doit(s);
}
}
That's all, we can test it in Main
class Main {
public static void main(String[] args) {
new MyClass(str -> System.out.println(str)).startWork("Hello print it!!!");
}
}
We can also use lambda with method parameter which take functional interface.
class Main {
public static void main(String[] args) {
test(str ->System.out.println(str), "Hello world!!!");
}
public static void test(DoWork d, String str) {
d.doit(str);
}
}
For more about Lambda you can see http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
This is the full code:
new Thread(new Runnable() {
@Override
public void run() {
//do things
}
}).start();
Lambda expressions let you express instances of single-method classes more compactly.
https://stackoverflow.com/users/5221149/andreas noticed that deep down there is a difference:
The anonymous class declaration still creates a separate anonymous class, while the lambda adds a hidden method and uses invokedynamic, basically using method reference, so there is a difference behind the scene. Functionally they are equivalent, though.