25 May 2013

Java8, my first attempt to write simple lambda (closure)-based example

Java8 will introduce lambda expressions (a.k.a closure), So it will introduce many functional concepts to compete with other powerful langs such as scala.


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);
    }

}

Post a Comment