2020-03-04

Complete guide to java lambda expressions

Lambda expressions

Lambda expression in Java 8 brings functional programming style into Java platform.

A simple example

Let’s start from a simple example which starts a thread and outputs some text to console.

 public class ThreadExample {
 public static void main(String[] args) {
 new Thread(new Runnable() {
 public void run() {
 System.out.println("Hello World!");
 }
 }).start();
 }
 }

In the above example only one line of code does the real work. All the rest are just boilerplate code. To increase productivity, boilerplate code should be removed as much as possible.

Lambda expressions style

public class LambdaThread {
 public static void main(String[] args) {
 new Thread(() -> System.out.println("Hello World!")).start();
 }
 }

Lambda expression () -> System.out.println("Hello World!") does the same thing as anonymous class, but using lambda expression is concise and elegant and easier to understand with less code. Less code means increasing productivity.


Few come concept we have to understand, Before lambda expressions

Lambda expressions

Lambda expressions have a very simple syntax to write. The basic syntax looks like (a1, a2) -> {}.

 list -> list.size()

 (x, y) -> x * y

 (double x, double y) -> x + y

() -> "Hello World"

(String operator, double v1, double v2) -> {
 switch (operator) {
 case "+":
 return v1 + v2;
 case "-":
 return v1 - v2;
 default:
 return 0;
 }
 }


Lambda expression’s body can return a value or nothing. If a value is returned, the type of return value must be compatible with target type. If an exception is thrown by the body, the exception must be allowed by target type’s throws declaration.



No comments:

Post a Comment