27 March 2013

Go functional the Java way (1)

Functional programming deals with functions as a High-order functions that can be used the same way the variables are used, so as the functions can by send as a parameters to other functions.

In Java, we can achieve this by sending an interface containing this simple function to some method.

If we have a function "sum" that looks like:

public static int sum(int[] arr) {
    int sum = 0;
    for (int i=0; i < arr.length; i++) {
            sum += arr[i];
    }
    return sum;
}

And we need to sum the array based on some condition, If Java supports passing functions to method, we could pass the function this way:

sum(new int[]{1, 2, 3, 4, 5}, function(int i){ return i%2 ==0 } )

But since Java doesn't, We should go the Java way doing that, notice the example below:


public class Main {
    public static void main(String[] args) {
        
        int sum = sum(new int[] {1, 2, 3, 4, 5}, new Predicate<Integer>() {
            public boolean test(Integer t) {
                return t >= 4 ;
            }
        });
        System.out.println(sum);
    }
    
    public static int sum(int[] arr, Predicate<Integer> accept) {
        int sum = 0;
        for (int i=0; i < arr.length; i++) {
            if (accept.test(arr[i]))
                sum += arr[i];
        }
        return sum;
    }
    
    interface Predicate<T>{
        boolean test(T t);
    }
}


Does the above code looks familiar?
It should, since the Collections.sort uses similar code to do custom sorting of a List.

In Java8 and according to http://www.dzone.com/links/r/why_we_need_lambda_expressions_in_java_part_1.html the syntax should be much simpler using lambda expression. It might look like Scala code:


sum(new int[]{1, 2, 3, 4, 5}, (Intger i) => i%2 == 0 )


Reference and code blocks from the above link.

No comments: