/java/

Java8 - Lambda simple examples

2015-01-03 23:19:06

Example 1

@FunctionalInterface
public interface VoidWorker {
    public void run();
}

old way invoke run using Annonymous class

VoidWorker voidWorker = new VoidWorker() {
    @Override
    public void run() {
        System.out.println("Worker invoked using Anonymous class");
    }
};
voidWorker.run();

new way invoke run using Lambda expression

VoidWorker voidWorker = () -> System.out.println("Worker invoked using Lambda expression");
voidWorker.run();

Example 2

@FunctionalInterface
public interface SimpleAdditionCalc {
    public int run();
}
SimpleAdditionCalc simpleAdditionCalc = () -> 1 + 1;
int result = simpleAdditionCalc.run();
System.out.println(result);

Example 3

@FunctionalInterface
public interface AdditionParamCalc {
    public int run(int a, int b);
}
AdditionParamCalc additionParamCalc = (int a, int b) -> a + b;
int result2 = additionParamCalc.run(2, 3);
System.out.println(result2);
AdditionParamCalc additionParamCalc3 = (int a, int b) -> {
    a = a * 2;
    b = b * 2;
    return a + b;
};
int result3 = additionParamCalc3.run(2, 3);
System.out.println(result3);