Java 8 Lambda Expressions | Code Factory
2 min readDec 13, 2019
Reference Link : Link
Lambda expression is a new and important feature of Java which was included in Java SE 8.
Lambda expression facilitates functional programming, and simplifies the development a lot.
Syntax
(Arguments / parameters) -> {Body}
Java lambda expression is consisted of three components.
- Argument / Parameters: It can be empty or non-empty as well.
- Arrow-token: It is used to link arguments-list and body of expression.
- Body: It contains expressions and statements for lambda expression.
Java Example without Lambda Expression
interface Drawable {
public void draw();
}public class Main {
public static void main(String[] args) {
int width = 10;// without lambda, Drawable implementation using anonymous class
Drawable d = new Drawable() {
public void draw() {
System.out.println("Drawing " + width);
}
};
d.draw();
}
}
Output :
Drawing 10
Java Example with Lambda Expression
@FunctionalInterface
// It is optional
interface Drawable {
public void draw();
}public class Main {
public static void main(String[] args) {
int width = 10;// with lambda
Drawable d2 = () -> {
System.out.println("Drawing " + width);
};
d2.draw();
}
}
Output :
Drawing 10
Java Lambda Expression Example: No Parameter
interface Sayable {
public String say();
}public class Main {
public static void main(String[] args) {
Sayable s = () -> {
return "I have nothing to say.";
};
System.out.println(s.say());
}
}
Output :
I have nothing to say.
Java Lambda Expression Example: Single Parameter
interface Sayable {
public String say(String name);
}public class Main {
public static void main(String[] args) {// Lambda expression with single parameter.
Sayable s1 = (name) -> {
return "Hello, " + name;
};
System.out.println(s1.say("Code"));// You can omit function parentheses
Sayable s2 = name -> {
return "Hello, " + name;
};
System.out.println(s2.say("Factory"));
}
}
Output :
Hello, Code
Hello, Factory
Java Lambda Expression Example: Multiple Parameters
interface Addable {
int add(int a, int b);
}public class Main {
public static void main(String[] args) {// Multiple parameters in lambda expression
Addable ad1 = (a, b) -> (a + b);
System.out.println(ad1.add(10, 20));// Multiple parameters with data type in lambda expression
Addable ad2 = (int a, int b) -> (a + b);
System.out.println(ad2.add(100, 200));
}
}
Output :
30
300
Java Lambda Expression Example: Foreach Loop
public class Main {
public static void main(String[] args) {List<string> list = new ArrayList<string>();
list.add("Code");
list.add("Factory");list.forEach((n) -> System.out.println(n));
}
}
Output :
Code
Factory