Lambda Expressions

A Lambda expression is a new feature in Java 8 that enables it to treat a function as method arguments and a concise code representation of an anonymous function that can be passed. Anonymous means no name, as it is a function with anonymous it can have parameters too. A lambda expression is commonly used to implement simple events listeners/ callbacks, or in functional programming or we can say, It's used to provide the implementation of a functional interface.
    A lambda expression is an anonymous function that has a body, return type, arguments, and exceptions.

    Syntax:-     
  • (parameters) -> expression
  • (parameters) -> { statements; }
    Example:-
  • () -> "codeforsolution";
  • () -> {};
  • (String str) -> str.lenght();
  • () -> System.out.println("Code for solution");
  • (a, b) -> a.toUpperCase + b.toUpperCase();
  • (a, b) ->  System.out.println(a+b); 
Example:- 
Without lambda Expression.
       
Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Run method from Runnable"); } }; new Thread(runnable).start();
With Lambda Expression.
Runnable runnable = () -> System.out.println("Run method from Runnable"); new Thread(runnable).start();


Comparator Without Lambda Expression
Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } };
With Lambda Expression
Comparator<Integer> comparator = (o1, o2) -> o1.compareTo(o2);
Post a Comment (0)
Previous Post Next Post