Java8 Lambda expression tutorial
In this tutorial we will be looking at lambda expressions which are very popular now a days. Lambdas can reduce a lot of boilerplate code like anonymous object creation etc. This tutorial is created by taking android framework in mind but will be relevant to any java framework using java8.
First of all we have to setup lambda expression support on out android studio as right now java8 is experimental on Android studio. You can simply add this support by using retrolambda as shown in this tutorial.
Learning curve for lambda is quite steep but once you learn it you wont be able resist yourself from using it. Lets get started.
Lambdas for Single Method Interface
First use case is single method interface like Android’s OnClickListener.
1 2 3 |
public interface OnClickListener { void onClick(View v); } |
Here is simple snippet for OnClickListener.
1 2 3 4 5 6 |
btnLoadPosts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setVisibility(View.VISIBLE); } }); |
Here first we have created a Anonymous class of View.OnClickListener interface which will be called later. This code can be greatly reduced in using lambda.
1 2 3 |
btnLoadPosts.setOnClickListener(view -> { view.setVisibility(View.VISIBLE); }); |
and if we are calling single function only then we can remove this curly braces.
1 |
btnLoadPosts.setOnClickListener(view -> view.setVisibility(View.VISIBLE)); |
So 6 lines of code reduced to single line!
Single Method Interface which do not return object
In last example method was provided with a View object now lets look at how to deal if none object is returned. In this example we will be creating our own interface with single method.
1 2 3 |
interface MyInterface{ void simpleMethod(); } |
Now lets create Anonymous class of this as we done in last example.
1 2 3 4 5 6 |
btnLoadPosts.setMyInterface(new MyInterface() { @Override public void simpleMethod() { hello(); } }); |
Here we have called hello function which do some work. Now lets see lambda version of this.
1 2 3 |
btnLoadPosts.setMyInterface(() -> { hello(); }); |
Now we reference simpleMethod using () [braces]. Finally we can remove curly braces also.
1 |
btnLoadPosts.setMyInterface(() -> hello()); |
One thing to notice here is that we do not need semicolon after hello() function. That’s all for now.
Please comment for any clarification.