700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > lambda表达式java_Java Lambda表达式

lambda表达式java_Java Lambda表达式

时间:2020-07-19 20:32:09

相关推荐

lambda表达式java_Java Lambda表达式

lambda表达式java

Java lambda expression can be considered as one of the coolest feature introduced in Java 8. It is Java’s first step into functional programming. A Java lambda expression can be considered as a function which can be created without belonging to any class. Also, it can be passed around as if it was an object and executed on demand.

Java lambda表达式可以被视为Java 8中引入的最酷的功能之一。 这是Java进入函数式编程的第一步。 Java lambda表达式可以视为可以创建的函数,而无需属于任何类。 同样,它可以像对象一样传递并按需执行。

Java Lambda表达式 (Java Lambda Expression)

Basically, Lambda Expression is a concise representation of an anonymous function that can be passed around. So, it has the following properties:

基本上,Lambda Expression是可以传递的匿名函数的简洁表示。 因此,它具有以下属性:

Anonymous: We can say anonymous because it doesn’t have an explicit name like a method would normally have. So, it’s definitely less to write and think about.匿名:我们可以说匿名,因为它没有像方法通常那样的显式名称。 因此,编写和思考的内容肯定要少得多。Function: It can be thought of as a function because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.函数:可以将其视为函数,因为lambda并不像方法那样与特定类关联。 但是像方法一样,lambda具有参数列表,主体,返回类型以及可能抛出的异常列表。Passed around: A lambda expression can be passed as argument to a method or stored in a variable.传递:可以将lambda表达式作为参数传递给方法或存储在变量中。Concise: We don’t need to write a lot of boilerplate like we do for anonymous classes.简洁:我们不需要像编写匿名类那样编写很多样板文件。

Technically, Lambda expressions do not allow us to do anything that we did not do prior to Java 8. It’s just that we don’t need to write clumsy code in order to use the behaviour parameterisation.

从技术上讲,Lambda表达式不允许我们执行Java 8之前没有做的任何事情。只是为了使用行为参数化,我们不需要编写笨拙的代码。

Java Lambda表达式示例 (Java Lambda Expression Example)

An example would certainly help to get a clear idea. ConsiderAppleclass:

举个例子肯定有助于弄清楚一个主意。 考虑Apple类:

public class Apple {String color;Double weight;public String getColor() {return color;}public void setColor(String color) {this.color = color;}public Double getWeight() {return weight;}public void setWeight(Double weight) {this.weight = weight;}}

If we want to write a custom comparator to compare the Apples by weight, until Java 7 we used to write it in the following way:

如果我们想编写一个自定义比较器来按重量比较苹果,那么在Java 7之前,我们通常通过以下方式编写它:

Comparator<Apple> byWeight = new Comparator<Apple>() {public int compare(Apple a1, Apple a2){return a1.getWeight().compareTo(a2.getWeight());}};

Now, using Lambda Expression, we can write the same thing as:

现在,使用Lambda Expression,我们可以编写与以下内容相同的东西:

Comparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

Java Lambda表达式说明 (Java Lambda Expression Explanation)

Let’s dig into the individual pieces in this expression:

让我们深入研究此表达式中的各个部分:

A list of parameters: In this case it mirrors the parameters of the compare method of a

Comparator – two Apple objects.参数列表:在这种情况下,它镜像了a的compare方法的参数

比较器 –两个Apple对象。An arrow: The arrow -> separates the list of parameters from the body of the lambda.箭头:箭头->将参数列表与lambda主体分开。The body of the lambda: Compare two Apples using their weights. The expression is considered

the lambda’s return value.lambda的主体:比较两个苹果的重量。 该表达式被认为

Lambda的返回值。

Java 8 Lambda Expression用法 (Java 8 Lambda Expression usage)

Let’s look at some use case examples of java lambda expression.

让我们看一下Java lambda表达式的一些用例示例。

A boolean expression:(List list) -> list.isEmpty()布尔表达式:((List list) -> list.isEmpty()Creating objects:() -> new Apple()创建对象() -> new Apple()Consuming from an object:(Apple a) -> { System.out.println(a.getWeight()); }从对象消耗(Apple a) -> { System.out.println(a.getWeight()); }(Apple a) -> { System.out.println(a.getWeight()); }Select/extract from an object:(String s) -> s.length()从对象中选择/提取(String s) -> s.length()Produce a single value by performing computation on two values:(int a, int b) -> a * b通过对两个值执行计算来产生单个值(int a, int b) -> a * bCompare two objects:(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())比较两个对象(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())

Java功能接口 (Java Functional Interfaces)

It is obvious to wonder where such expressions are allowed? Previously we saw a lambda expression to replace the Comparator implementation. we can also use it as follows:

很明显想知道在哪里允许这样的表达式? 以前,我们看到了一个lambda表达式来替换Comparator实现。 我们还可以如下使用它:

List<String> greenApples = listOfApples.stream().filter(a -> a.getColor().equals("Green")).collect(Collectors.toList());

Here,filter()method expects a Predicate. We just passed a lambda instead of the required interface.

在这里,filter()方法需要一个Predicate 。 我们只是传递了一个lambda而不是所需的接口。

Basically, we can use them in the context of Functional Interfaces. Now, what exactly are Functional Interfaces?

基本上,我们可以在Functional Interfaces的上下文中使用它们。 现在,功能接口到底是什么?

In a nutshell, a Functional Interface is an interface that specifies exactly one abstract method.

简而言之,功能接口是一种接口,它恰好指定了一种抽象方法。

Some known Functional Interfaces in Java areComparator,Runnable,ActionListener, Callable, etc.

Java中一些已知的功能接口是ComparatorRunnableActionListener, Callable等。

Also note that an interface is still a functional interface even if it defines one or more default methods, as long as it defines a single abstract method.

还要注意,即使接口定义了一个或多个默认方法,只要它定义了一个抽象方法,它仍然是一个功能接口。

And of course, we can always define custom functional interfaces apart from the default ones provided by Java.

当然,除了Java提供的默认接口之外,我们总是可以定义自定义功能接口。

Java Lambda expressions lets us provide the implementation for the abstract method of the functional interface directly, inline and the whole expression is treated as an instance of a concrete implementation of that interface.

Java Lambda表达式使我们可以直接,内联地直接为功能接口的抽象方法提供实现,并将整个表达式视为该接口的具体实现的实例。

Java Lambda表达式与匿名类 (Java Lambda Expressions vs Anonymous class)

Considering our previous examples, the same things can be achieved using the anonymous class as well, but the code will be clumsier if we are writing the implementation inline.

考虑前面的示例,使用匿名类也可以实现相同的目的,但是如果我们内联编写实现,代码将变得更加笨拙。

Let’s see an example ofRunnable. Consider aprocessmethod that takes in aRunnableinstance:

让我们看一个Runnable的例子。 考虑一个采用Runnable实例的process方法:

public class RunnableDemo {public static void process(Runnable r){r.run();}}

Without using Lambda, we can implement it as:

无需使用Lambda,我们可以将其实现为:

Runnable runnableWithAnonymousClass = new Runnable() {@Overridepublic void run() {System.out.println("I am inside anonymous class implementation.");}};process(runnableWithAnonymousClass);

Using the lambda expression:

使用lambda表达式:

Runnable runnableWithLambda = () -> System.out.println("I am inside Lmabda Expression.");process(runnableWithLambda);

Also, in cases where we are using this Runnable implementation only once, we can also provide it directly while calling the process method:

同样,在仅使用一次此Runnable实现的情况下,我们也可以在调用process方法时直接提供它:

process(() -> System.out.println("I am inside Lambda Expression."));

功能描述符 (Function Descriptor)

An important thing to understand while working with lambda expression is a functional descriptor. The signature of the abstract method of the functional interface essentially describes the signature of the lambda expression. We call this abstract method a function descriptor.

使用lambda表达式时要了解的重要事项是函数描述符。 功能接口的抽象方法的签名实质上描述了lambda表达式的签名。 我们将此抽象方法称为函数描述符。

For example, the Runnable interface can be viewed as the signature of a function that accepts nothing and returns nothing (void) because it has only one abstract method calledrun, which accepts nothing and returns nothing (void).

例如,Runnable接口可以看作是不接受任何内容且不返回任何内容(无效)的函数的签名,因为它只有一个称为run抽象方法,该方法不接受任何内容且不返回任何内容(无效)。

That’s all for the Java Lambda Expressions.

Java Lambda表达式就这些了。

Reference: API Doc

参考: API文档

翻译自: /16703/java-lambda-expression

lambda表达式java

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。