Lambda Expressions




Lambda Expressions :

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection In addition, new concurrency features improve performance in multicore environments.

Why Lambdas?

A lambda expression is a block of code that you can pass around so it can be executed later, just once or multiple times.


Syntax of Lambda Expressions

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses
  • The arrow token, ->
  • A body, which consists of a single expression or a statement block.
Syantax Structure :

(arg1, arg2...) -> { body }
(type1 arg1, type2 arg2...) -> { body }

Example :


(int a, int b) -> {  return a + b; }
() -> System.out.println("Hello World");
(String s) -> { System.out.println(s); }
() -> 42
() -> { return 3.1415 };

Examples of Lambda Expression

Thread can be initialize as,

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//Old way:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from thread");
}
}).start();
//New way:
new Thread(
() -> System.out.println("Hello from thread")
).start();

List can be iterated as,


1
 2
 3
 4
 5
 6
 7
 8
 9
10
//Old way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}
//New way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));
//or we can use :: double colon operator in Java 8
list.forEach(System.out::println);



Comments