Kenji Kenji - 5 months ago 12
Android Question

Java Lambda expressions: Why should I use them?

I heard that it's a concept named Lambda expressions in C# and it's added in java 8.
I'm android developer so it's my concern that why this concept added to Java. Certainly it have a good advantage but I could not find out that.

I Implement it to my project by adding this to Cradle:

android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
defaultConfig {
applicationId "com.example.mytest"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"

//for using java 8 and it's features like lambda expressions
jackOptions { enabled true }


}

compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}


and write some Lambda Expression like this that I googled:

button4.setOnClickListener( e -> Toast.makeText(Main2Activity.this, "test", Toast.LENGTH_SHORT).show());


I really lock for good example of Using Lambda-Expression in android.

Answer

I finally find this good example:

Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.

A lambda expression is characterized by the following syntax −

parameter -> expression body

and this is a good example:

 public class Java8Tester {
        public static void main(String args[]){
            Java8Tester tester = new Java8Tester();

        //with type declaration
        MathOperation addition = (int a, int b) -> a + b;

        //with out type declaration
        MathOperation subtraction = (a, b) -> a - b;

        //with return statement along with curly braces
        MathOperation multiplication = (int a, int b) -> { return a * b; };

        //without return statement and without curly braces
        MathOperation division = (int a, int b) -> a / b;

        System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
        System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
        System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
        System.out.println("10 / 5 = " + tester.operate(10, 5, division));

        //with parenthesis
        GreetingService greetService1 = message ->
                System.out.println("Hello " + message);

        //without parenthesis
        GreetingService greetService2 = (message) ->
                System.out.println("Hello " + message);

        greetService1.sayMessage("Mahesh");
        greetService2.sayMessage("Suresh");
    }

    interface MathOperation {
        int operation(int a, int b);
    }

    interface GreetingService {
        void sayMessage(String message);
    }

    private int operate(int a, int b, MathOperation mathOperation){
        return mathOperation.operation(a, b);
    }
}
Comments