Java 8 Functionals

Functionals and Lambdas

This post is basically an introduction to the new Java 8 features regarding functional programming. In previous versions of Java the functional paradigm was a little bit nasty to employ because of the overhead in verbosity that almost turn the code unreadable. Functional programming is absolutely possible in Java, the problem is that the syntax is based on anonymous interfaces that hold just one method. So to create a functional you had to emulate the concept by doing something like this

public interface Transform<T,U>{
    U transform(T object);
}

And keep creating anonymous classes of if like

Transform<String,String> a=
    new Transform<String, String>() {
            @Override
            public String transform(String object) {
                // TODO Auto-generated method stub
                return null;
            }
};

And then passing it to some high order function called map

public static <T,U> List<U> map(
    List<T> data,Transform<T, U> mapper
){
        List<U> out=new ArrayList<U>();
        for(T el : data){
            out.add(mapper.transform(el));
        }
        return out;
}

in this nasty way:

map(strs,new Transform<String, String>() {
            @Override
            public String transform(String object) {
                // TODO Auto-generated method stub
                return object.toLowerCase();
            }
});

To avoid this boilerplate code needed to emulate the concept of function as a variable java 8 add some sugar syntax to help us remove this sick stuff of the way and invite us to write more with less keystrokes.

With the introduction of @FunctionalInterface annotation we can use lambda notation to replace our anonymous interfaces. This way the previous code could be replaced by something like

map(strs,(String token) -> {return token.toLowerCase();});

which by no means is a great improvement. We should note, however, that this is just sugar syntax and tha we are dealing with anonymous classes and so we don't have functions as pure first class citizens nevertheless we should be happy to the effort that java guys did to help us enjoy a little bit more of functional thinking in java code

More code here