Java 8 – Lambda Expressions

本文介绍Java 8中引入的Lambda表达式及其用法,包括语法结构、功能接口的概念,并通过实例对比了使用Lambda表达式前后代码的变化。
A lambda expression is basically just a block of code that you can pass around to be executed later – once, or multiple times. Many other languages support them, so you’ve probably already used them if you’ve coded in a language other than C/C++/Java/C# (they’re also often referred to as ‘Closures’, ‘Anonymous Functions’, or ‘Blocks’).

 

A quick example to show the syntax: sorting list of custom elements

Often you would solve this by defining an anonymous inner class that implements the Comparator interface. With Java 8, you can instead provide a lambda expression that defines the comparison:

 

You have a list (dateItems) of objects that have a member of type Date.

 

List<DatedItem> dateItems = <…get items…>

dateItems.sort( (DatedItem a, DatedItem b) -> { returna.date().compareTo(b.date() } );

 

 

Syntax

-          General structure: ( arguments ) -> { body }

-          A left and right side separated by a -> token. The left side defines the incoming parameters. The right side defines the code to execute.

-          A lambda expression can have zero, one or more parameters.

-          The type of the parameters can be explicitly declared or it can be inferred from the context. e.g. (int a) is same as just (a)

-           Parameters are enclosed in parentheses and separated by commas. e.g. (a, b) or (int a, int b) or (String a, int b, float c)

-           Empty parentheses are used to represent an empty set of parameters. e.g. () -> 42

-           When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a

-          The body of the lambda expressions can contain zero, one or more statements.

-          If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

-          When there is more than one statement in body than these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

 

Functional Interfaces

A ‘functional interface’ is an interface that declares a single abstract method. For example java.lang.Runnable (declares only run() method), or java.awt.event.ActionListener (declares only actionPerformed(ActionEvent) method). Wherever a functional interface is used, a lambda can be used in its place. E.g. :

 

newThread( () -> System.out.println("thread started") ).start();

 

Examples

 

-- Thread execution --

//Old way:

new Thread(new Runnable() {

    @Override

    public void run() {

        System.out.println("Hello from thread");

    }

}).start();

 

//New way:

new Thread( () -> System.out.println("Hello from thread") ).start();

 

-- Button handling --

//Old way:

button.addActionListener(new ActionListener() {

    @Override

    public void actionPerformed(ActionEvent e) {

        System.out.println("The button was clicked using old fashion code!");

    }

});

 

//New way:

button.addActionListener( (e) -> { System.out.println("The button was clicked. From lambda expressions !"); });

 

-- List processing --

//Old way:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

for(Integer n: list) {

    System.out.println(n);

}

 

//New way:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

list.forEach(n -> System.out.println(n));

 

-- Map reduce --

//Old way:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

intsum = 0;

for(Integer n : list) {

    intx = n * n;

    sum = sum + x;

}

System.out.println(sum);

 

//New way:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

intsum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();

System.out.println(sum);

 

** Note use of new Java8 Stream APIs. (see java.util.stream.Stream).

 

 

Comparator is a functional interface?

Above we used a lambda expression instead of a Comparator in the ArrayList.sort() method. In order for this to work, Comparator must be a functional interface. When I was looking through this I got hung up on why Comparator was a functional interface since a functional interface is defined as: “More precisely, a functional interface is defined as any interface that has exactly one abstract method.” However, if you look at the Comparator interface, you’ll see that it actually has two declared methods: compare() and equals().  To clear up any confusion – the explanation is: “The interface Comparator is functional although it explicitly declares two methods, because only one is abstract; equals is an explicit declaration of a concrete method inherited from Object that, without this declaration, would otherwise be implicitly declared.

 

 

There’s more that can be said about lambda expressions (specifically about lexical scoping and how ‘this’ is handled), but this email is getting too long so consider this just a primer J.

 -------------

 

In Java8, an anonymour inner class can access a non-final local variable, and this this applies to both anonymous inner classes and lambdas expressions. That’s because Java8 compiler does that for us automatically. That also makes lambda expressions easier to access the outer variable. However, as Jingwei mentioned, we can’t modify its value (or modify the reference of container type, but we can modify the contents in container, of course), it’s immutable.

源码链接: https://pan.quark.cn/s/a4b39357ea24 在网页构建领域中,CSS3(层叠样式表第三版)为程序员们提供了多样化的视觉表现手法和用户交互功能。在此案例中,我们聚焦于一种普遍的用户交互设计——"CSS3鼠标指针停留在图片上时的放大效果",即当用户将鼠标光标移动至图片上时,图片会自动进行放大,从而增强了用户的参与度和视觉冲击力。此类效果经常应用于商品展示或图像预览环节,有助于提升网站的整体用户体验。 我们需要掌握HTML5中的`<img>`标签,它是用于嵌入图像的基本组件。在`<img>`标签内部,我们可以通过`src`属性来设定图像的地址,`alt`属性用于在图像无法加载时提供替代说明文字,此外还包括`width`和`height`属性用于设定图像的尺寸。 ```html <img src="image.jpg" alt="图片的说明文字" width="200" height="200"> ``` 构建图片在鼠标悬停时放大这一功能的关键在于CSS3的`:hover`伪类选择器。`:hover`用于选取鼠标光标悬停其上的元素,结合transform属性,我们可以便捷地实现图片的放大操作。以下是一个基础的示例: ```css img { transition: transform 0.3s ease; /* 引入过渡效果 */ } img:hover { transform: scale(1.2); /* 鼠标悬停时,图片放大到原尺寸的120% */ } ``` 在这段代码里,`transition`属性设置了图像在变化过程中的过渡效果,`0.3s`代表过渡持续的时间,`ease`是预设的缓动效果,使得变化过程更加流畅。`...
内容概要:本文系统研究了基于最优滑模控制的永磁同步电机(PMSM)调速系统模型,并通过Simulink平台实现了完整的仿真实验。研究聚焦于滑模控制在电机调速中的应用,重点对比了经典滑模、改进滑模与最优滑模三种控制策略的性能差异,深入分析了最优滑模控制在提升系统动态响应速度、增强抗干扰能力及改善稳态精度方面的优势。文章详细阐述了电机数学建模、控制器设计、稳定性分析与仿真验证全过程,突出了最优滑模控制在有效抑制抖振现象、提高系统鲁棒性方面的关键技术特点。; 适合人群:具备自动控制原理、电机控制理论基础及Simulink仿真技能的电气工程、自动化、控制科学与工程等相关领域的研究生、科研人员以及从事高性能电机驱动系统开发的工程技术人员。; 使用场景及目标:①为高等院校和科研机构开展先进电机控制算法的教学与科研工作提供理论依据和仿真案例;②为工业界高性能伺服系统、新能源汽车电驱动系统等领域的控制器设计提供技术参考与验证手段;③帮助研究人员深入掌握滑模控制的设计方法、参数整定技巧及其在实际工程系统中的实现路径。; 阅读建议:建议读者结合提供的Simulink模型进行同步操作与仿真,重点关注不同滑模控制器的结构设计与参数设置,通过对比仿真结果直观理解最优滑模控制的优越性。同时,可在此基础上探索将最优滑模控制与自抗扰、预测控制等先进控制理论相结合,进一步拓展其在复杂非线性系统中的应用研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值