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. Consider Apple class:

举个例子肯定有助于弄清楚一个主意。 考虑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表达式的一些用例示例。

  1. A boolean expression: (List list) -> list.isEmpty() 布尔表达式 :( (List list) -> list.isEmpty()
  2. Creating objects: () -> new Apple() 创建对象() -> new Apple()
  3. 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()); }
  4. Select/extract from an object: (String s) -> s.length() 从对象中选择/提取(String s) -> s.length()
  5. Produce a single value by performing computation on two values: (int a, int b) -> a * b 通过对两个值执行计算来产生单个值(int a, int b) -> a * b
  6. Compare 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 are Comparator, 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 of Runnable. Consider a process method that takes in a Runnable instance:

让我们看一个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 called run, which accepts nothing and returns nothing (void).

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

That’s all for the Java Lambda Expressions.

Java Lambda表达式就这些了。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16703/java-lambda-expression

lambda表达式java

lambda表达式java_Java Lambda表达式相关推荐

  1. c++ lambda函数_C++ Lambda表达式

    利用Lambda表达式,可以方便的定义和创建匿名函数.Lambda 表达式把函数看作对象.Lambda 表达式可以像对象一样使用,比如可以将它们赋给变量和作为参数传递,还可以像函数一样对其求值. 当一 ...

  2. Linq表达式、Lambda表达式你更喜欢哪个?

    什么是Linq表达式?什么是Lambda表达式? 如图: 由此可见Linq表达式和Lambda表达式并没有什么可比性. 那与Lambda表达式相关的整条语句称作什么呢?在微软并没有给出官方的命名,在& ...

  3. Java代码简化之朗母达表达式(Lambda Express)

    Java代码简化之朗母达表达式(Lambda Express) 本文目录: Lambda Express基本概念 Lambda Express的解析 1. Lambda Express基本概念 λ表达 ...

  4. C#3.0之神奇的Lambda表达式和Lambda语句

    "Lambda 表达式"是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型.所有 Lambda 表达式都使用 Lambda 运算符 =>,该运算符读 ...

  5. Linq表达式和Lambda表达式用法对比

    什么是Linq表达式?什么是Lambda表达式? 前一段时间用到这个只是,在网上也没找到比较简单明了的方法,今天就整理了一下相关知识,有空了再仔细研究研究 public Program() { Lis ...

  6. python基础学习1-三元表达式和lambda表达式

    #!/usr/bin/env python # -*- coding:utf-8 -*- 三元运算 if else 的简写name ="alex" if 1==1 else &qu ...

  7. c++11标准:匿名函数(匿名表达式)lambda

    lambda: C++11提供了对匿名函数的支持,称为Lambda函数(也叫Lambda表达式). Lambda表达式具体形式如下: 匿名函数定义/匿名表达式声明:[capture](paramete ...

  8. 【Kotlin】Kotlin 中使用 Lambda 表达式替代对象表达式原理分析 ( 尾随 Lambda - Trailing Lambda 语法 | 接口对象表达式 = 接口#函数类型对象 )

    文章目录 一.尾随 Lambda - Trailing Lambda 语法 二.Kotlin 中使用 Lambda 表达式替代对象表达式原理 1.Lambda 替换对象表达式 2.原理分析 3.示例分 ...

  9. LINQ查询表达式和LAMBDA点标记方法基础

    在上一篇文章中,我们介绍了LINQ的一些基本用法,这一篇我们来看下另一种更简洁更优雅的表达式,Lambda表达式,也可以叫做点标记方法. 相信大家在实际工作中都用到过这两种方式,下面我们还是用实例来看 ...

最新文章

  1. crontab添加定时任务
  2. key位置 win10生成的ssh_Git实现ssh免密登录
  3. JAVA-初步认识-第八章-继承-单继承和多重继承
  4. 四位数码管秒表 c语言编程,4位共阴极数码管秒表设计仿真与程序
  5. Python编程常见错误表现形式与原因分析
  6. bioconductor 安装包_R语言 | 你知道自己的Bioconductor版本么?
  7. 真香!谷歌终与美国国防部合作,签署百万美金云服务合同
  8. 烧了1.18亿美元融资后,谷歌GV投资的无人机公司宣布倒闭
  9. android动画送礼物,【Android】直播App礼物弹窗及连送礼物动画
  10. autojs颜色渐变效果
  11. android备份手机号码,Android QQ同步助手3.2 保证号码备份“不丢人”
  12. js URL 地址参数格式化
  13. codeception apiTest入门
  14. 计算机网络覆盖的地理范围分类,计算机网络按地理范围可分为什么
  15. 台式电脑c语言如何安装,台式电脑怎么安装电源 组装机正确安装电源的方法
  16. 网线每根的含义以及类别和距离传输问题
  17. 异常(The host [tomcat_server] is not valid)(Nginx配置异常)
  18. 限制服务器访问ip(或端口)
  19. PhD Debate-8 | 迈向常识知识的高级语义理解
  20. faster r-cnn训练、测试、检测(含批量检测图片)

热门文章

  1. 九度OJ 1193:矩阵转置 (矩阵计算)
  2. error parsing xml:unbound prefix
  3. VB.net中的sender和e
  4. Java BigDecimal 数据类型的运算
  5. oracle中循环读出一个表的信息插入到另外一个表中
  6. Android MonkeyRunner
  7. 使用tcl文件分配管脚
  8. [cpp] 重载运算符规律总结
  9. WebDevHelper -- RESTful服务和Ajax开发时的利器
  10. A MULTI-TASK FRAMEWORK WITH FEATURE PASSING MODULE FOR SKIN LESION CLASSIFICATION AND SEGMENTATION