How to use Lambda in Java 8?

Java has been added lambda expressions an important new functionality,
through which functional programming is possible. First, we briefly explain how to use
lambda expressions with some examples:

function with funktional Interfaces.

Argument List    Arrow Token    Body
(int x, int y)   ->             x + y
(String s)       ->             {System.out.println(s);}
()               ->             6
  • First Example with Type declaration
package com.nourit.java8.LambdaExpressions;

public class LambdaExpressionsExample {

  public static void main(String args[]) {
    Addition addition = (int a, int b) -> a + b;// with type declaration
    System.out.println("15 + 5 = " + addition.operation(15, 5));
  }

  interface Addition {
    int operation(int a, int b);
  }
}
  • Second Example without Type declaration
package com.nourit.java8.LambdaExpressions;

public class LambdaExpressionsExample {

  public static void main(String args[]) {
    Addition addition = (a, b) -> a + b;// without type declaration
    System.out.println("15 + 5 = " + addition.operation(15, 5));
  }

  interface Addition {
    int operation(int a, int b);
  }
}
  • Third Example with return
package com.nourit.java8.LambdaExpressions;

public class LambdaExpressionsExample {

  public static void main(String args[]) {
    Addition addition = (a, b) -> {// with return statement
      return (a + b);
    };
    System.out.println("15 + 5 = " + addition.operation(15, 5));
  }

  interface Addition {
    int operation(int a, int b);
  }
}

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*