You are on page 1of 2

28/05/2018 Java 8 - JavaSampleApproach

System.out.println(doMathOperation(2, 1, multiplication));
}

Syntax:

Argument List Arrow Token Body Note

(arg1, arg2…) ­> { body }

with type
(int a, int b) ­> a + b
declaration

no type
(a, b) ­> a + b
declaration

with return
(int a, int b) ­> {return (a + b)}
statement

a ­> a*a*a no parenthesis

() ­> 42 no arguments

{System.out.print(
(String s) ­> returns nothing
s);}

– A lambda expression can have zero, one or more parameters. 
– No need to declare type of a parameter. 
– No need to write parenthesis around parameter if there is only one parameter
(required if more). 
– No need to use curly braces in expression body if there is only one statement
(required if more). 
– No need to use return keyword if there is only one statement. The compiler
returns the value automatically.

>>> More details at: Java 8 – Lambda Expressions

Functional Interfaces

Functional Interfaces is an interface with only one abstract method inside.

public interface MyFuncInterface {


void doWork();
}

http://javasampleapproach.com/java-tutorial/java-8#Lambda_Expressions 2/8
28/05/2018 Java 8 - JavaSampleApproach

@FunctionalInterface annotation is used to annotate for Functional Interface. So
compiler will throw errors when the interface is not a valid Functional Interface.

@FunctionalInterface
public interface MyFuncInterface {
void doWork();
void doAnotherWork();
}

Invalid '@FunctionalInterface' annotation; MyFuncInterface is not a functional


interface

Apply Functional Interfaces:

@FunctionalInterface
public interface MyFuncInterface {
void doWork();
}
 
public class MainApp {

public static void executeFunction(MyFuncInterface func) {


func.doWork();
}
 
public static void main(String[] args) {
executeFunction(new MyFuncInterface() {

@Override
public void doWork() {
System.out.println("invoke Function using Anonymous Inner Class");
}
});

// with Lambda Expression


executeFunction(() -> System.out.println("invoke Function using Lambda Expre
}
}

For Functional Interface with only one method, we can make code lean and
beautiful with Lambda Expression, it seem like that we pass a method as
argument to a function.

>>> More details at: Java 8 – Functional Interfaces

Method References

http://javasampleapproach.com/java-tutorial/java-8#Lambda_Expressions 3/8

You might also like