SoFunction
Updated on 2025-03-11

Detailed explanation of the usage example of Lambda expression in Android

Detailed explanation of the usage example of Lambda expression in Android

Java8 has indeed introduced some very distinctive functions, such as Lambda expressions, streamAPI, interface default implementation, etc. Lambda expressions are the lowest compatible with Android 2.3 systems in Android, and their compatibility is still good. Lambda expressions are essentially an anonymous method. They have neither method names nor access modifiers and return value types. The code written with them will be more concise and easy to read.

Basic writing of expressions

If you want to use Lambda expressions or other new features of Java8 in your Android project, first we need to install the Java8 version of JDK, and then add the following configuration in app/:

android {
  ...
  defaultConfig {
     = true
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Then you can start using Lambda expressions:

For example, the way to open a child thread using Lambda expression is:

// Traditional waynew Thread(new Runnable() {
  @Override
  public void run() {
    // Handle business logic  }
}).start();

// Using Lambda Expressionsnew Thread(() -> {
  // Handle business logic}).start();

Whether from the number of lines of code or indentation structure, the writing of Lambda expressions is more concise. Why can I write this way? Let's take a look at the source code of the Runnable interface:

public interface Runnable {
  void run();
}

Any interface with only one method to be implemented can use the Lambda expression writing method.

2. Customize the interface and then use Lambda expressions

Create a new MyListener interface, and there is only one method to be implemented in the interface. The only difference from the previous one is that it has parameters and return values:

public interface MyListener {
  String run(String str1, String str2);
}

Then the anonymous implementation method for creating the MyListener interface using Lambda expression is as follows:

MyListener listener = (String str1, String str2) -> {
  String result = str1 + str2;
  return result;
};

In addition, Java can automatically infer the parameter types in Lambda expressions through context, so it can be further simplified:

MyListener listener = (str1, str2) -> {
  String result = str1 + str2;
  return result;
};

Use Lambda expressions in

Click events in Android use Lambda expressions:

(new () {
  @Override
  public void onClick(View view) {
    // Handle click events  }
});

After using Lambda expression:

((v) -> {
  // Handle click events});

In addition, when the interface has only one parameter, we can further simplify and remove the brackets outside the parameters:

(v -> {
  // Handle click events});

Thank you for reading, I hope it can help you. Thank you for your support for this site!