Home  >  Article  >  Java  >  Java Lambda expression usage example analysis

Java Lambda expression usage example analysis

WBOY
WBOYforward
2023-04-18 16:01:03765browse

Lambada Introduction

lambda expression is a new feature added in Java 8. It introduces the concept of functional programming in Java. So what is functional programming?

Functional programming: Functional programming is a mathematics-oriented abstraction that describes calculation as an expression evaluation.

What we usually call object-oriented programming belongs to imperative programming. The difference between functional programming and imperative programming is:

  • Functional programming is concerned with data mapping, and imperative programming is related to the steps to solve problems.

  • Functional programming relationships between relationship types (algebraic structures), imperative programming relationships steps to solve problems.

The essence of functional programming:

The function in functional programming does not refer to the function in the computer, but to mathematics The function in is the mapping of independent variables. That is: the value of a function only depends on the value of the function parameter and does not depend on other states.

Functional programming in the strict sense means programming without using mutable variables, assignments, loops, and other imperative control structures.

The benefits of functional programming:

The benefits of functional programming are mainly caused by immutability. Without mutable state, functions are referentially transparent and have No Side Effect.

The above are some basic concepts, but we may have less exposure to these aspects, so at first I felt that functional programming was a rare thing.

Simple example

Talk is cheap, show me the code!

Let’s start with the simplest example, which may also be the most introduced. Example. Ha ha!

Add a monitor to the button.

Use anonymous inner classes to add.

submit.addActionListener(new ActionListener() {
	@Override
	public void actionPerformed(ActionEvent e) {
		JOptionPane.showMessageDialog(null, "点击了确定按钮", "确定", JOptionPane.INFORMATION_MESSAGE);
	}
});

Disadvantages of this method: a lot of template code is used, and the only code that is really necessary is the code in the method body. Therefore, the Lambda expression introduced in Java 8 can simplify this kind of code (of course, there are limitations. Not all anonymous inner classes can be used, which will be mentioned later.).

Use Lambda expressions to simplify code

submit.addActionListener((e)->{
		JOptionPane.showMessageDialog(null, "点击了确定按钮", "确定", JOptionPane.INFORMATION_MESSAGE);
});

Lambda expression is an anonymous method that passes behavior like data.

Explanation

It can be seen that the simplified code expression using Lambda expressions becomes clearer, and there is no need to write cumbersome template code. .

Further simplification

The parameter brackets and the curly brackets of the code body can also be omitted (When there is only one parameter, the parentheses can be omitted, and when there is only one line of code, The curly braces can be omitted).

ActionListener listener = e->JOptionPane.showMessageDialog(null, "点击了确定按钮", "确定", JOptionPane.INFORMATION_MESSAGE);

Summary
When using a Lambda expression instead of an anonymous inner class to create an object, the code block of the Lambda expression will replace the method body that implements the abstract method. Lambda is equivalent to An anonymous method.

Components of Lambda expression

lambda expression consists of three parts:

  • Formal parameter list. The formal parameter list allows omission of formal parameter types. If there is only one parameter in the parameter list, the parentheses in the parameter list can be omitted.

  • Arrow (->). English dash and greater than sign.

  • Code block. If the code block has only one sentence, the curly braces can be omitted. If there is only one return statement, you can omit return, and the lambda expression will automatically return the value of this statement.

Note:
The reason why the formal parameter list can be omitted is because the compiler can perform type inference, for example:

List<Dog> dogs1 = new ArrayList<Dog>();

List<Dog> dogs2 = new ArrayList<>();

is used above Diamond syntax, you can omit the things inside the angle brackets, this is the role of type inference.
But type inference is not omnipotent, not all can be inferred, so sometimes, you still need to add formal parameter type explicitly, for example:

Don’t worry about it yet The specific function of this code.

BinaryOperator b = (x, y)->x*y;
//上面这句代码无法通过编译,下面是报错信息:无法将 * 运算符作用于 java.lang.Object 类型。
The operator * is undefined for the argument type(s) java.lang.Object, java.lang.Object
//添加参数类型,正确的代码。
BinaryOperator<Integer> b = (x, y)->x*y;

So, type inference is not omnipotent. If the compiler cannot infer it, it is our mistake. Don't rely too much on the compiler. Sometimes, it is still necessary to add parameter types explicitly. Of course, this requires more practice.

Functional interface

As we learned earlier, Lambda expressions can replace anonymous inner classes to simplify code and express clearly. So what are the prerequisites for using Lambda expressions? -- Functional Interface

The type of Lambda expression, also known as the target type (Target Type), must be a functional interface (Functional Interface). The so-called functional interface refers to: An interface that only contains one abstract method. (Can contain multiple default methods and static methods, but there must be only one abstract method).
Note: Java 8 provides a special annotation: @FunctionalInterface. Used to mark an interface as a functional interface, so that it will be checked during compilation. If the interface contains multiple abstract methods, the compiler will report an error.

上面使用 Lambda 表达式来为按钮添加了监视器,可以看出来,Lambda 表达式 代替了 new ActionListener()对象。

所以 Lambda 的表达式就是被当成一个对象。

例如:

ActionListener listener = e->JOptionPane.showMessageDialog(null, "点击了确定按钮", "确定", JOptionPane.INFORMATION_MESSAGE);

从上面这个例子中可以看出来,Lambda 表达式实现的是匿名方法–因此它只能实现特定函数式接口中的唯一方法。
所以 Lambda 表达式有下面两种限制:

Lambda 表达式的目标类型必须是明确的函数式接口。 Lambda 表达式只能为函数式接口创建对象。Lambda只能实现一个方法,因此它只能为含有一个抽象方法的接口(函数式接口)创建对象。 介绍几个 Java 中重要的函数接口

Java Lambda expression usage example analysis

从这种表可以看出来,抽象方法的名字反而不是最重要的了,重要的是参数和返回值。 因为在写 Lambda 表达式的时候,也不要使用 抽象方法名了。

上面使用几个简单的例子来说明上面接口的应用:

测试代码

import java.text.ParseException;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;

public class Test {
	public static void main(String[] args) throws ParseException {
		//Lambda 表达式中的构造器引用,用于简化代码。
		Creat<Dog> c = Dog::new;
		Dog dog = c.creat("小黑", 15);
		System.out.println(dog.toString());
		
		Predicate<String> predicate = (words)->{
			return words.length() > 20;
		};
		assert predicate.test("I love you yesterday and today!") : "长度小于20";
		assert !predicate.test("God bless you!") : "长度小于20";
		System.out.println("------------------------");
		
		Consumer<Dog> consumer = System.out::println;
		consumer.accept(dog);
		System.out.println("------------------------");

		Function<Dog, String> function = (dogObj)->{
			return dogObj.getName();
		};
		System.out.println(function.apply(dog));
		System.out.println("------------------------");
		
		Supplier<Dog> supplier = ()->{
			return new Dog("大黄", 4);
		};
		System.out.println(supplier.get());
		
		//一元操作符
		UnaryOperator<Boolean> unaryOperation = (flag)->{
			return !flag;
		};
		System.out.println(unaryOperation.apply(true));
		
		BinaryOperator<Integer> binaryOperator = (x, y)->x*y;
		int result = binaryOperator.apply(999, 9999);
		System.out.println(result);
	}
}

测试使用的实体类

public class Dog {
	private String name;
	private int age;
	
	public Dog(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Dog [name=" + name + ", age=" + age + "]";
	}
}

自定义函数式接口

@FunctionalInterface
public interface Creat<T> {
	public T creat(String name, int age);
}

运行截图就不放了,感兴趣的可以试一下。

说明
我这里直接使用 Lambda 创建了对象,然后调用了这个对象的方法(就是lambda 的代码块部分),真正使用的时候,都是直接传递 Lambda 表达式的,这种方法并不推荐,但是可以让我们很好的理解为什么? 可以看出来,Lambda 表达式的作用,最后还是需要调用 重写的抽象方法的,只不过使用表达更加清晰,简化了代码。

例如:

		List<Dog> dogs = new ArrayList<>();
		dogs.add(new Dog("大黄", 2));
		dogs.add(new Dog("小黑", 3));
		dogs.add(new Dog("小哈",1));
		//将行为像数据一样传递,使用集合的 forEach 方法来遍历集合,
		//参数可以是一个 Lambda 表达式。
		Consumer<? super Dog> con = (e)->{
			System.out.println(e);
		};
		dogs.forEach(con);
		System.out.println("--------------------------\n");
	
		//直接传递 Lambda 表达式,更加简洁
		dogs.forEach(e->System.out.println(e));
		System.out.println("--------------------------\n");

		//使用方法引用,进一步简化(可以看我的另一篇关于方法引用的博客)
		dogs.forEach(System.out::println);
		System.out.println("--------------------------\n");

		//使用 Lambda 对集合进行定制排序,按照年龄排序(从小到大)。
		dogs.sort((e1, e2)->e1.getAge()-e2.getAge());
		dogs.forEach(System.out::println);

可以看出来,通过使用 Lambda 表达式可以,极大的简化代码,更加方便的操作集合。值得一提的是:Lambda 表达式 和 Stream 的结合,可以拥有更加丰富的操作,这也是下一步学习的方向。

运行截图:

Java Lambda expression usage example analysis

The above is the detailed content of Java Lambda expression usage example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete