I've wrote some simple example to show the powerful of functional interfaces and the shortcut syntax of lambda expressions.
I've wrote the example once by Java8 syntax and once by Java7 syntax.
public class HelloJava8{
public static void main(String[] args){
int v1 = 10, v2 = 30;
int result = performOperation(v1, v2, (a, b) -> a + b);
System.out.println("result: " + result);
result = performOperation(v1, v2, (x, y) -> x - y);
System.out.println("result: " + result);
Operation op = (i, j) -> i * j;
result = performOperation(v1, v2, op);
System.out.println("result: " + result);
}
// funcationl interface, an interface with one method
private static int performOperation(int x, int y, Operation op){
return op.doOperation(x, y);
}
interface Operation{
int doOperation(int x, int y);
}
}
Here's the example with Java7 (notice how Java8 code is much compact):
public class HelloJava7{
public static void main(String[] args){
int v1 = 10, v2 = 30;
int result = performOperation(v1, v2, new Operation(){
public int doOperation(int x, int y){
return x + y;
}
});
System.out.println("result: " + result);
result = performOperation(v1, v2, new Operation(){
public int doOperation(int x, int y){
return x + y;
}
});
System.out.println("result: " + result);
Operation op = new Operation(){
public int doOperation(int i, int j){
return i * j;
}
};
result = performOperation(v1, v2, op);
System.out.println("result: " + result);
}
private static int performOperation(int x, int y, Operation op){
return op.doOperation(x, y);
}
interface Operation{
int doOperation(int x, int y);
}
}
No comments:
Post a Comment