您现在的位置是:首页 > 文章详情

JAVA8给我带了什么——lambda表达

日期:2019-03-29点击:310

JAVA8给我带了什么——lambda表达
这此年来我一直从事.NET的开发。对于JAVA我内心深处还是很向往的。当然这并不是说我不喜欢.NET。只是觉得JAVA也许才是笔者最后的归处。
MK公司是以.NET起家的。而笔者也因为兄弟的原因转行.NET。虽然有时候还是会拿起JAVA相关的知识回味一下。尽可能的不让自己忘记。但是时代的进步却把我狠狠甩到了后面去。
现在笔者终于离开了M公司。我想回去做JAVA,却发现笔者已经跟不上JAVA时候。在笔者转行.NET的时候,JAVA的版本才到 1.6。现在都1.8了。主要的是这个段时间发现很大的变化。所以就想看看JAVA8底能带给我什么。
笔者回来做JAVA就是想知道的第一件事——JAVA8里面有什么。不知道Oracle公司收了Sun公司之后为什么一直没有动作,在加上笔者忙着搞.NET开发。JAVA的事情就失去了信息,对于JAVA7笔者不是没有感知,主要是JAVA8听说变化很大。可以说是一个大版本的变化。所以笔者回来的时候就想知道——JAVA8里面有什么。同时笔者在这里声明这一系列主要是记得笔者自身从JAVA8得到了什么,如果有要学JAVA8同学,本系列只能作参考。
笔者是从事.NET的开发,相对JAVA以前而言。.NET有一些功能真的不错。lambda表达示可以说成为.NET开发人员不可能离开的一部分。以前的JAVA可是没有这个功能的。.NET可以把一个方法当做一个参数和变量来赋值。JAVA在这一块就弱了很多了。所以JAVA很多时候在设计模式上面做很大的体现。
把一个方法函数当前一个参数和变量来用的行为我们称为行为参数化。那么他有什么好处呢?策略模式相信大家可能都听过。不如笔者就以《JAVA实战》这本书的例子为例吧。假设我是一个农户,家里种苹果的。今年大丰收,好多苹果。我把每一个苹果都打标签。并把相关苹果的颜色,重量,大小,品种都记录到数据库中。
为了方便日后的查看,笔者自己想一款软件。在写的过其中,笔者希望有这样子功能——能以颜色来查看相关的苹果。所以笔者设计一个农民类,他有一个功能——根据颜色查看苹果。

Apple类:

复制代码
1 package com.aomi;
2
3 public class Apple {
4 private String color;
5 private double weight;
6 private String typeName;
7 private int size;
8
9 public String getColor() {
10 return color;
11 }
12
13 public void setColor(String color) {
14 this.color = color;
15 }
16
17 public double getWeight() {
18 return weight;
19 }
20
21 public void setWeight(double weight) {
22 this.weight = weight;
23 }
24
25 public String getTypeName() {
26 return typeName;
27 }
28
29 public void setTypeName(String typeName) {
30 this.typeName = typeName;
31 }
32
33 public int getSize() {
34 return size;
35 }
36
37 public void setSize(int size) {
38 this.size = size;
39 }
40
41 @Override
42 public String toString() {
43 return "Apple [color=" + color + ", weight=" + weight + ", typeName=" + typeName + ", size=" + size + "]";
44 }
45
46
47
48 }
复制代码
Peasant类

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Peasant {
7
8 public List GetApplesByColor(List sources, String color) {
9
10 List suiteApples = new ArrayList<>();
11
12 for (Apple apple : sources) {
13
14 if (apple.getColor().equals(color))
15 suiteApples.add(apple);
16
17 }
18
19 return suiteApples;
20 }
21 }
复制代码

Main:

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Main {
7
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10
11 // 查找红色的苹果
12
13 Peasant peasant = new Peasant();
14
15 List rApples = peasant.GetApplesByColor(getSources(), "red");
16
17 for (Apple apple : rApples) {
18 System.out.println(apple.toString());
19 }
20
21 }
22
23 public static List getSources() {
24
25 List sources = new ArrayList<>();
26 Apple apple1 = new Apple();
27
28 apple1.setColor("red");
29 apple1.setTypeName("hot");
30 apple1.setSize(12);
31 apple1.setWeight(34.2);
32 Apple apple2 = new Apple();
33
34 apple2.setColor("grayred");
35 apple2.setTypeName("hot");
36 apple2.setSize(12);
37 apple2.setWeight(34.2);
38
39 Apple apple3 = new Apple();
40
41 apple3.setColor("green");
42 apple3.setTypeName("hot");
43 apple3.setSize(12);
44 apple3.setWeight(34.2);
45
46 sources.add(apple1);
47 sources.add(apple2);
48 sources.add(apple3);
49
50 return sources;
51 }
52
53 }
复制代码
运行结果:

写完之后,感觉得很完美。过一段时间,突然发现好像不行。这个功能不好,我需要大小来查看苹果。于是修改一下,在Peasant类增加一个新的方法。根据大小来查看:

复制代码
1 public List GetApplesBySize(List sources, int size) {
2
3 List suiteApples = new ArrayList<>();
4
5 for (Apple apple : sources) {
6
7 if (apple.getSize() > size)
8 suiteApples.add(apple);
9
10 }
11
12 return suiteApples;
13 }
复制代码
好吧。看起来也不错,那么有没有想过后面还有可能会以重量来查看苹果。只能在加一个方法了。那么问题来了。一但功能多。整类会看起来一个点复杂。理解有一点难度。在没有lambda表达的时候,JAVA会用一下有一点策略模式的方式实现。把相关的比较操作变成一个类。如下
Lookup接口类:

1 package com.aomi;
2
3 public interface Lookup {
4 boolean handle(Apple apple);
5 }
ColorRedLookup类:

复制代码
1 package com.aomi;
2
3 public class ColorRedLookup implements Lookup {
4
5 @Override
6 public boolean handle(Apple apple) {
7 // TODO Auto-generated method stub
8 return apple.equals("red");
9 }
10
11 }
复制代码
SizeLookup类:

复制代码
1 package com.aomi;
2
3 public class SizeLookup implements Lookup {
4
5 @Override
6 public boolean handle(Apple apple) {
7 // TODO Auto-generated method stub
8 return apple.getSize() > 120;
9 }
10
11 }
复制代码
Peasant类:

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Peasant {
7
8 public List LookupApple(List sources, Lookup lookup) {
9
10 List suiteApples = new ArrayList<>();
11
12 for (Apple apple : sources) {
13
14 if (lookup.handle(apple))
15 suiteApples.add(apple);
16
17 }
18
19 return suiteApples;
20 }
21 }
复制代码
Main:

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Main {
7
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10
11 // 查找红色的苹果
12
13 Peasant peasant = new Peasant();
14
15 List rApples = peasant.LookupApple(getSources(), new ColorRedLookup());
16
17 for (Apple apple : rApples) {
18 System.out.println(apple.toString());
19 }
20
21 }
22
23 public static List getSources() {
24
25 List sources = new ArrayList<>();
26 Apple apple1 = new Apple();
27
28 apple1.setColor("red");
29 apple1.setTypeName("hot");
30 apple1.setSize(12);
31 apple1.setWeight(34.2);
32 Apple apple2 = new Apple();
33
34 apple2.setColor("grayred");
35 apple2.setTypeName("hot");
36 apple2.setSize(12);
37 apple2.setWeight(34.2);
38
39 Apple apple3 = new Apple();
40
41 apple3.setColor("green");
42 apple3.setTypeName("hot");
43 apple3.setSize(12);
44 apple3.setWeight(34.2);
45
46 sources.add(apple1);
47 sources.add(apple2);
48 sources.add(apple3);
49
50 return sources;
51 }
52
53 }
复制代码
上面的这种从某些方面来讲笔者不是很喜欢。虽然这种方式看起来会比较人性化。但是相比笔者还是喜欢前面那一种增加方法的。这是个人的想法。

List rApples = peasant.LookupApple(getSources(), new ColorRedLookup());
看完这段代码之后我们就可以发现一个问题。是不是每一个条件查找我都要建一个类呢?好像不是很好玩了。所以还是试一下我们试一下lambda表达。上面的代码不用修改太多。只要main方法里面就可以了。

复制代码
1 public static void main(String[] args) {
2 // TODO Auto-generated method stub
3
4 // 查找红色的苹果
5
6 Peasant peasant = new Peasant();
7
8 List rApples = peasant.LookupApple(getSources(), (Apple apple) -> apple.getColor().equals("red"));
9
10 for (Apple apple : rApples) {
11 System.out.println(apple.toString());
12 }
13
14 rApples = peasant.LookupApple(getSources(), (Apple apple) -> apple.getSize() > 120);
15
16 for (Apple apple : rApples) {
17 System.out.println(apple.toString());
18 }
19
20 }
复制代码
是不是非常简单呢。不用在建什么类了。所以lambda表达的好处很明显的。笔者想要什么查找规则只要改变一下规则就行了。如下用大小来查找。

List rApples = peasant.LookupApple(getSources(), (Apple apple) -> apple.getSize() > 12);
lambda表达给人感觉就是一个缩小版本的方法。往后面看的话,这种感觉你们会变的更加。但是在学习ambda表达的时候,有一些细节点还是要注意的。

语法点:(parameters)->expression或是(parameters)->{statements;}
学习会查看lambda表达的签名。即称函数描述符
从语法点我们可以知道
左边parameters:是表示参数,就好比如方法函数的参数是一样子的。
中间->:是固定的。
右边expression或是{statements;}:是表示只能接受表达式,或是加大括号的语句。称为主体
举一些例子来加强一下吧

1.()-> {}//有效
2.()->"aomi"//有效
3.()->{return "aomi";}//有效
4.()->return "aomi "+ 1;//无效,主体是语句,要加上{}
5.()->{"aomi";}//跟上面的相反,主体是表达式,去掉{}
说到lambda表达的签名,这边就不得不提到一个概念函数式接口。他的定义是这样子,只要接口里面只有一个抽象方法都是可以算是函数式接口。举一个JAVA是里面的函数式接口

复制代码
1 package java.lang;
2
3 @FunctionalInterface
4 public interface Runnable {
5 /**
6 * When an object implementing interface Runnable is used
7 * to create a thread, starting the thread causes the object's
8 * run method to be called in that separately executing
9 * thread.
10 *


11 * The general contract of the method run is that it may
12 * take any action whatsoever.
13 *
14 * @see java.lang.Thread#run()
15 */
16 public abstract void run();
17 }
复制代码
Runnable就是一个函数式接口。他只有一个run抽象方法。上面有一个注解类@FunctionalInterface他就是用于说明当前类是一个函数式接口。不过好像事实上你可以不用加上他。
AomiRunnable类:

复制代码
1 package com.aomi;
2
3 public interface AomiRunnable {
4
5 void run();
6
7 }
复制代码
Main:

复制代码
1 public class Main {
2
3 public static void main(String[] args) {
4 Runnable run = () -> {
5 System.out.println("i am runnble");
6 };
7
8 AomiRunnable aRun = () -> {
9 System.out.println("i am aomirunnble");
10 };
11
12 run.run();
13
14 aRun.run();
15
16 }
17 }
复制代码
运行结果:

看到上面的代码不要奇怪。这个正好可以说明lambda表达的神奇之处。我们可以看到笔者定义了俩个函数式接口的变量。一个是JAVA里面自带的,一个是笔者自己写的。俩个都可以正常的运行。可是笔者自已写的好像没有加入@FunctionalInterface。那是不是@FunctionalInterface没有用呢?那还是有的。看下面就知道了。当你写错了就会提示你写的不是函数式接口。

所以还是加上吧。这样子显得也专业一点吗?
有了函数式接口,就必须说一下函数描述符。他事实上就是lambda表达的签名。他是从哪里来的呢?很简单的,看接口的唯一方法就行了。就好例如上面Runnable类,他的方法就是无参数,无返回值。你可写才这样子表示一下:()->{}。为什么要有函数描述符呢?你们可以这样子理解。JAVA里面有很多自己写好的函数式接口。如果你没有函数描述符的话,你又何如明白什么时候用到哪一个呢?如下

Predicate类:T -> boolean
Function类:T ->R
看到上面函数描述符的话,你是不是就可以知道他们的用法呢。所以了解函数描述符的话,你就可以很清楚的明白自己要用JAVA里面的哪个函数式接口。同时还可以提高你在写代码过程的速度。目前JAVA里面有哪一些函数式接呢?自己去看吧。在rt.jar里面的

还是让笔者再举个例子吧。笔者希望按苹果的大小来非序。所以我们可一定要用到List类的sort方法了。sort方法里面以Comparator类作为参数。Comparator类是一个函数式接口。抽象方法如下

int compare(T o1, T o2);
所以函数描述符是(T,T)-> int。知道这些之后就好办了。

复制代码
1 public static void main(String[] args) {
2
3 List apples = getSources();
4
5 apples.sort((Apple a1, Apple a2) -> a2.getSize() - a1.getSize());
6
7 for (Apple apple : apples) {
8
9 System.out.println(apple);
10 }
11
12 }
复制代码
运行结果:

看起很方便吧。

lambda表达的确不错。使得用JAVA8开发的同学代码更加的人性化。但是JAVA8还加入另一种功能叫方法引用。看一下例子。

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Main {
7
8 public static void main(String[] args) {
9
10 List apples = getSources();
11
12 apples.sort(Main::AppleComparator);
13
14 for (Apple apple : apples) {
15
16 System.out.println(apple);
17 }
18
19 }
20
21 public static int AppleComparator(Apple a1, Apple a2) {
22 return a2.getSize() - a1.getSize();
23 }
24
25 public static List getSources() {
26
27 List sources = new ArrayList<>();
28 Apple apple1 = new Apple();
29
30 apple1.setColor("red");
31 apple1.setTypeName("hot");
32 apple1.setSize(13);
33 apple1.setWeight(34.2);
34 Apple apple2 = new Apple();
35
36 apple2.setColor("grayred");
37 apple2.setTypeName("hot");
38 apple2.setSize(12);
39 apple2.setWeight(34.2);
40
41 Apple apple3 = new Apple();
42
43 apple3.setColor("green");
44 apple3.setTypeName("hot");
45 apple3.setSize(14);
46 apple3.setWeight(34.2);
47
48 sources.add(apple1);
49 sources.add(apple2);
50 sources.add(apple3);
51
52 return sources;
53 }
54
55 }
复制代码
主要修改的地方:

apples.sort(Main::AppleComparator);
增加的地方:

1 public static int AppleComparator(Apple a1, Apple a2) {
2 return a2.getSize() - a1.getSize();
3 }
在使用方法引用的时候,要注要一点,好像要静态方法才行。如果不的话。会报错的。

让笔者好好说明下吧。方法引用并不是可以随便写的。他是有依据的。总共有三种:

静态方法,必须要符合(arg)->ClassName.staticMehtod(arg).的格式。
任意类型的实例方法,必须符合(object,rest)->object.instanceMethod(rest)的格式。
对象实例的实例方法,必须符合(args)->obj.instanceMethod(args)的格式。
我们可以看到方法引用就是针于单一方法的lambda表达的。 我们都知道Function函数接口的lambda表达的用法。好!假设笔者在Apple类中加入这样子的方法

1 public int testApple(Apple a) {
2 return a.getSize() - 100;
3 }
然后在Main的代码中是这样子写的。

Function fun = Apple::testApple;
不好意思他会报错。

让我们看一下Function的函数描述符吧。(T)-> R.好像跟testApple方法是一样子的话,那为什么不行呢? 让我们把Function变成为他等同的一个lambda表达的写吧。

(Apple a) -> 123//123可以是任意的数字。
跟笔者上面说的三点都不符合,当然不行了。所以想要可行的话,必须把testApple方法变成静态的。这样子就合适第一种了。关于比较Comparator类,JAVA8提供了一个comparing静态方法。他接受了一个Function参数。并返回一个Comparator类对象。修改一下。

apples.sort(comparing((Apple a) -> a.getSize()));
记得一个要引入

import static java.util.Comparator.comparing;
又因为方法引用的关系

(Apple a) -> a.getSize() 等于 Apple::getSize()
我们就可以把他修改为

apples.sort(comparing(Apple::getSize));
笔者用一个以前的例子吧。排序苹果Main的类全部代码

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import static java.util.Comparator.comparing;
6
7 public class Main {
8
9 public static void main(String[] args) {
10
11
12 List apples = getSources();
13
14 apples.sort(comparing(Apple::getSize));
15
16 for (Apple apple : apples) {
17
18 System.out.println(apple);
19 }
20
21 }
22
23 public static int AppleComparator(Apple a1, Apple a2) {
24 return a2.getSize() - a1.getSize();
25 }
26
27 public static List getSources() {
28
29 List sources = new ArrayList<>();
30 Apple apple1 = new Apple();
31
32 apple1.setColor("red");
33 apple1.setTypeName("hot");
34 apple1.setSize(13);
35 apple1.setWeight(34.2);
36 Apple apple2 = new Apple();
37
38 apple2.setColor("grayred");
39 apple2.setTypeName("hot");
40 apple2.setSize(12);
41 apple2.setWeight(34.2);
42
43 Apple apple3 = new Apple();
44
45 apple3.setColor("green");
46 apple3.setTypeName("hot");
47 apple3.setSize(14);
48 apple3.setWeight(34.2);
49
50 sources.add(apple1);
51 sources.add(apple2);
52 sources.add(apple3);
53
54 return sources;
55 }
56
57 }
复制代码
运行结果:

有了方法引用之后,在有一种叫构造引用的话,相信大家都不会有什么吃惊的地方了。

Supplier app = Apple::new;
等于

Supplier app = ()->new Apple();
笔者就不多讲了。

关于lambda表达的知识大部分是这样子。笔者说实话吧。JAVA8加入lambda表达让笔者一定也没有感到兴奋。因为.NET那边都写烂了。至少上面讲到的知识让笔者没有什么新鲜感。到是方法引用有一点味。但是下面的知识点却让笔者提了一点兴趣了。

复合lambda表达。什么意思!就是把多个lambda表达用or或and的概念放到一起使用。好比如上面的排序例子。可以反序的。修改下面的代码

apples.sort(comparing(Apple::getSize).reversed());
加上.reversed()之后

没有加之前

还有哦,还可以修改为

apples.sort(comparing(Apple::getSize).reversed().thenComparing(Apple::getWeight));
一个排序条件不够,可以加哦。

让我们换另外一些方式来看看吧。

Main类:

复制代码
public static void main(String[] args) {

 Function<Integer, Integer> add = (Integer a) -> a + 2; Function<Integer, Integer> multiply = (Integer a) -> a * 4; Function<Integer, Integer> andThen = add.andThen(multiply); Function<Integer, Integer> compose = add.compose(multiply); System.out.println("andThen结果:" + andThen.apply(2)); System.out.println("compose结果:" + compose.apply(2)); }

复制代码
运行结果:

这个结果说明一个问题

andThen是multiply (add(x))。先执行了add,然后在multiply
compose是add(multiply(x))。先执行了multiply ,然后在add
对于andThen比较好理解。笔者不喜欢的是compose。为什么?一般开发人员喜欢看其名知其意。compose的英文意思是构成,写作,还有组成的意思。有一点难理解。
让我们在看一个奇神的点吧。

复制代码
1 package com.aomi;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.function.Predicate;
6
7 public class Main {
8
9 public static void main(String[] args) {
10
11 Predicate query = (Apple a) -> a.getSize() > 13;
12
13 query = query.and((Apple a) -> a.getWeight() < 20);
14
15 List apples = fliter(query);
16
17 for (Apple apple : apples) {
18
19 System.out.println(apple);
20 }
21
22 }
23
24 public static List fliter(Predicate pred) {
25 List nSources = new ArrayList<>();
26 List sources = getSources();
27 for (Apple apple : sources) {
28 if (pred.test(apple))
29 nSources.add(apple);
30 }
31 return nSources;
32 }
33
34 public static List getSources() {
35
36 List sources = new ArrayList<>();
37 Apple apple1 = new Apple();
38
39 apple1.setColor("red");
40 apple1.setTypeName("hot");
41 apple1.setSize(13);
42 apple1.setWeight(55.2);
43 Apple apple2 = new Apple();
44
45 apple2.setColor("grayred");
46 apple2.setTypeName("hot");
47 apple2.setSize(12);
48 apple2.setWeight(34.2);
49
50 Apple apple3 = new Apple();
51
52 apple3.setColor("green");
53 apple3.setTypeName("hot");
54 apple3.setSize(14);
55 apple3.setWeight(34.2);
56
57 Apple apple4 = new Apple();
58
59 apple4.setColor("green");
60 apple4.setTypeName("hot");
61 apple4.setSize(19);
62 apple4.setWeight(12.2);
63
64 sources.add(apple1);
65 sources.add(apple2);
66 sources.add(apple3);
67 sources.add(apple4);
68
69 return sources;
70 }
71
72 }
复制代码
本来集合时面有四个苹果,大小值大于13的有俩个苹果。所以当我们把条件用and在加上的时候—— 重量小于20.结果只有一个。

原文地址https://www.cnblogs.com/hayasi/p/10621965.html

原文链接:https://yq.aliyun.com/articles/695962
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章