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.

Here is simple snippet for OnClickListener.

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.

and if we are calling single function only then we can remove this curly braces.

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.

Now lets create Anonymous class of this as we done in last example.

Here we have called hello function which do some work. Now lets see lambda version of this.

Now we reference simpleMethod using () [braces]. Finally we can remove curly braces also.

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.

guru

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...

  • Pingback: Using Retrofit2 and RxJava - AndroidSRC()

  • Mirror, mirror, on the wall

    “6 lines of code reduced to single line”??? I can write the original code as a single line, too. Albeit longer:

    btnLoadPosts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setVisibility(View.VISIBLE); } });

    Yes, the lambda form is more terse but it is also more cryptic and less clear and less intuitive.

    • This way you can write whole application in single line. Its get more easy with time and if you once shifted to lambda then you cant go back…:p