Let's learn Java8 (2) - Lambda expressions

Introduction to Lambda

What is a Lambda expression, it is simply an anonymous function expression. So a lambda expression is essentially a function, but it doesn't have a function name.

Lambda expressions have the following characteristics:

  • anonymous, it has no function name
  • The essence is a function. In addition to the function name, it has a parameter list, function content (method body), and return type.
  • Concise, sometimes the type of the parameter can be omitted
  • Passable, Lambda expressions can be stored as a variable

The basic syntax of Lambda is:

(参数列表) -> 表达式

or

(参数列表) -> { 表达式; }

Where to use Lambda

Lambda expressions can be used wherever there is a functional interface.

Definition of functional interface:一个接口里面只有一个抽象方法。

Take the Runnable interface as an example, it is a functional interface, and the usage of Runnable is shown in the following code:

Thread thread = new Thread(new Runnable() {
	@Override
	public void run() {
		System.out.println("run...");
	}
});
thread.start();
Thread.sleep(100);

Since Runnable is a functional interface, Lambda can be used to represent replacement, and the replacement is as follows:

// 方式2
Thread thread2 = new Thread(() -> System.out.println("run2..."));
thread2.start();
Thread.sleep(100);

The content of the Lambda expression here is: () -> System.out.println("run2..."), which has no parameters, no return value, and only one method body. This expression can also be written as:

Thread thread2 = new Thread(() -> { 
    System.out.println("run2..."); // 注意这里;结尾
});

Note: After curly braces are added, the statement inside the method body must have ; at the end

There is also a functional interface Callable, whose internal call method needs to return a value. The usage of Callable is shown in the following code:

ExecutorService excutorService = Executors.newSingleThreadExecutor();
Future<String> future = excutorService.submit(new Callable<String>() {
	@Override
	public String call() throws Exception {
		return "Jim";
	}
});
String name = future.get();	
System.out.println(name);

Use lambda expressions:

ExecutorService excutorService = Executors.newSingleThreadExecutor();
Future<String> future = excutorService.submit(() -> "Jim2");
String name = future.get();	
System.out.println(name);

This () -> "Jim2"means that a Jim2 string is directly returned, and the returnkeyword can be omitted. Of course it can also be written as:

excutorService.submit(() -> {
	return "Jim2";
});

Next, we customize a functional interface and write it using Lambda expressions.

package learn.java8.ch2;

// 函数式接口
@FunctionalInterface
interface Caller {
	String call(String name);
}

class Serivce {
	private String name;
	
	public Serivce(String name) {
		this.name = name;
	}
	
	public String run(Caller caller) {
		return caller.call(name);
	}
}

public class LambdaTest2 {

	public static void main(String[] args) {
		Serivce service = new Serivce("Jim");
		String result = service.run((name) -> {
			return "My name is " + name;
		});
		System.out.println(result);
	}

}

At this point the Lambda expression is:

(name) -> {
	return "My name is " + name;
}

It has a parameter list, a method body, and a return result.

Note: the actual type of name is omitted, you can add:

String result = service.run((String name) -> {
	return "My name is " + name;
});

If there are multiple parameters, it is written as:

(String a, String b) -> {}or(a, b) -> {}

Lambda expressions can also be stored as variables, as shown in the following code:

package learn.java8.ch2;

import java.util.function.Consumer;

public class LambdaTest3 {

	static Consumer<String> consumer = (name) -> {
		System.out.println("My name is " + name);
	};

	static class Service {
		private String name;

		public Service(String name) {
			super();
			this.name = name;
		}

		public void run(Consumer<String> consumer) {
			consumer.accept(name);
		}
	}

	public static void main(String[] args) {
		// 可以直接调用
		consumer.accept("Jim");
		
		new Service("Tom").run(consumer);
	}

}

In this example an interface implementation is defined directly using a lambda expression:

static Consumer<String> consumer = (name) -> {
	System.out.println("My name is " + name);
};

It can be understood as assigning the Lambda expression to the consumer variable, or it can be understood as directly implementing the methods in the Consumer interface.

In short, lambda expressions can be used wherever there is a functional interface.

summary

This article mainly introduces the basic usage of Lambda expressions and how to use them in functional interfaces.

Regularly share technical dry goods, learn together, and progress together!

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324029914&siteId=291194637