The main goal of lambda expressions is to introduce the benefits of functional programming to Java. A lambda
is an anonymous function in Java. That is, a function which does not have a name, return type and access
modifiers. The lambda expression is an anonymous method (a method without a name) that is used to implement the abstract method of the functional interface.
Lambda expressions are also known as anonymous functions or closures.
Pros:
- less code
- easy to implement anonymous inner classes
- parameters to methods (pass lambda expressions as parameters to other methods)
Functional Interface
Interface -> functional interface: has one and only one abstract method
that method -> functional method
example: interface Runnable - run()
interface Comparator - compareTo()
Java 8 also provides us with an annotation called FunctionalInterface.
If you mark your interfaces with this annotation then you can only define one abstract method in that interface.
lambda expression without parameters
class A {
public void myMethod() {
System.out.println("inside my method");
}
}
public class Test {
public static void main(String{} args) {
A a = new A();
a.myMethod();
}
}
is the same as following code
class A {
public void myMethod() {
}
}
public class Test{
public static void main(String[] args) {
A a = () -> System.out.println("inside my method");
a.myMethod();
}
}
Lambda Expression with parameters
public interface Sum {
void add(int a, int b);
}
public class Test{
public static void main(String[] args) {
Sum s = (a, b) -> System.out.println("sum is " + (x + y));
s.add(10, 1);
}
}
Lambda with method body
public class Test {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 0; i <= 10; i++) {
System.out.println("Child Thread.");
}
};
Thread t = new Thread(r);
t.start();
for (int i = 0; i <= 10; i++ ) {
System.out.println("Parent Thread.");
}
}
}
//output: child thread x 10 times
parent thread x 10 times
Lambda with anonymous classes
public class Test {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("child thread");
}
}
});
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("main thread");
}
}
}
public class Test {
public static void main(String[] args) {
Thread t = new Thread(() -> {//run method doesn't need any parameters
for (int i = 0; i < 10; i++) {
System.out.println("child thread");
}
});
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("main thread");
}
}
}