简体   繁体   中英

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.

Lambda expression is just added to java to make your code mode expressive

. In the process, they streamline the way that certain common constructs are implemented.

The addition of lambda expressions also provided the catalyst for other new Java features, including the default method which lets you define default behavior for an interface method, and the method reference (described here), which lets you refer to a method without executing it.

So lambda expression do not make any change the way you code for android ,, it just enhances the way you code in java

you require to declare a functinal interface in order to use lambda expressions

a small example

// A functional interface. 
interface MyNumber { 
double getValue(); 
} 

class LambdaDemo { 
 public static void main(String args[]) 
 { 
MyNumber myNum;  // declare an interface reference 

// Here, the lambda expression is simply a constant expression. 
// When it is assigned to myNum, a class instance is 
// constructed in which the lambda expression implements 
// the getValue() method in MyNumber. 
myNum = () -> 123.45; 

  // Call getValue(), which is provided by the previously assigned 
// lambda expression. 
System.out.println("A fixed value: " + myNum.getValue()); 

// Here, a more complex expression is used. 
myNum = () -> Math.random() * 100; 

// These call the lambda expression in the previous line. 
System.out.println("A random value: " + myNum.getValue()); 
System.out.println("Another random value: " + myNum.getValue()); 

// A lambda expression must be compatible with the method 
// defined by the functional interface. Therefore, this won't work: 
//  myNum = () -> "123.03"; // Error! 
} 
 }

**sample output from the program **

A fixed value: 123.45 
A random value: 88.90663650412304 
Another random value: 53.00582701784129

Well there is nothing that Lambda expressions in Java-8 could do, that old Java couldn't. The only difference is that you need to type less and the code becomes more readable. (I always hated those anonymous classes)

Bringing Lambdas allows to write code in a functional style. For some areas (like business logic) it's a great advantage - results in a more compact and readable code.

In Java 8 a new Stream APIs were added. Lambdas is a part of that extension.

Stream APIs example .

Well, a lambda expression is just like a callable or Runnable interface, which has been in Java decades ago.

Which is good is that Java 8 brings with some interfaces conventions, to be implemented by your lambda expressions which are the most common use of implementation.

 Void=Consumer
 Boolean=Predicate
 Send/Return argument=Function

This would be a Function function example

           /**
 * In this example we use a Function, which receive an item and then return the same or another item through the pipeline.
 * Is the function used by mutable operators as Map or FlatMap
 *
 */
@Test
public void functionFunction() throws InterruptedException {
    String words = Stream.of("hello_functional_world")
                         .map(replaceWordsFunction())
                         .reduce("", String::concat);

    System.out.println(words);
}

private Function<String, String> replaceWordsFunction() {
    return a -> a.replace("_", " ");
}

You can take a look to these practical example that explain in details how this new function works and make your world a better place to live

https://github.com/politrons/reactive/blob/master/src/test/java/stream/Functions.java

Lambdas remove boilerplate code and make app more comprehensive. Especially it is true when you use RxJava library - if app work in reactive way, you need to define every operation in a separate chain blocks, which looks very clumsy without lambdas.

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); } } 

I post farsi version here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM