java代码(1)---Java8 Lambda
Lambda
一、概述 |
1、什么是Lambda表达式
//1.不需要参数,返回值为5
() -> 5 //2.接收一个参数(数字类型),返回其2倍的值
x -> 2 * x //3.接收2个参数(数字),并返回他们的差值
(x,y)-> x-y //4.接收2个int类型整数,返回他们的和
(int x, int y) -> x+y //5.接受一个String对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) ->System.out.print(s)
3.什么是函数式接口
在对上面进行举例说明之前,必须先来理解一下函数式接口,因为Lambda是建立在函数式接口的基础上的
记住!
(1)只包含一个抽象方法的接口,称为函数式接口
public class Lambda01 {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程1开启"+":"+Thread.currentThread().getName());
}
}).start(); new Thread(() -> System.out.println("线程2开启"+":"+Thread.currentThread().getName())).start();
Runnable runnable1= new Runnable(){
@Override
public void run() {
System.out.println("线程3开启"+":"+Thread.currentThread().getName());
}
};
Runnable runnable2=()-> System.out.println("线程4开启"+":"+Thread.currentThread().getName());
runnable1.run();
runnable2.run(); }
}
/*输出结果
* Hello world !
* Hello world !
* Hello world !
* Hello world !
*/
通过上面案例可以看出:通过Lambda表达式看去舒服清爽多了,2而通过匿名内部类代码总是不够整洁。
public class TestArray { public static void main(String[] args) {
String[] players = {"zhansgan", "lisi", "wangwu", "zhaoliu", "wangmazi"}; // 1.1 使用匿名内部类根据 surname 排序 players
Arrays.sort(players, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return (s1.compareTo(s2));
}
}); // 1.2 使用 lambda 排序,根据 surname
Arrays.sort(players, (String s1, String s2) -> s1.compareTo(s2)); //================================================================================================ // 2.1 使用匿名内部类根据 name lenght 排序 players
Arrays.sort(players, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return (s1.length() - s2.length());
}
}); // 2.2使用Lambda,根据name length
Arrays.sort(players, (String s1, String s2) -> (s1.length() - s2.length())); //================================================================================================== // 3.1 使用匿名内部类排序 players, 根据最后一个字母
Arrays.sort(players, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1));
}
}); // 3.2 使用Lambda,根据最后一个字母
Arrays.sort(players, (String s1, String s2) -> (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1)));
}
}
通过上面例子我们再来思考为什么Lambda表达式需要函数式接口?其实很简单目的就是为来保证唯一。
你的Runnable接口只要一个抽象方法,那么我用() -> System.out.println("Hello world !"),就只能代表run方法,如果你下面还有一个抽象方法,那我使用Lambda表达式,
那鬼才知道要调用哪个抽象方法呢。
二、方法引用
首先注意:方法引用,不是方法调用!方法引用,不是方法调用!方法引用,不是方法调用!
函数式接口的实例可以通过lambda表达式、方法引用、构造方法引用来创建,方法引用是lambda表达式的语法糖,任何用方法引用的地方都可由lambda表达式来替换,
但是并不是所有的lambda表达式都可以用方法引用来替换
举例
这就是一个打印集合所有元素的例子,value ->System.out.println(value)是一个Consumer函数式接口,这个函数式接口可以通过方法引用来替换
public class TestArray { public static void main(String[] args) {
List<String> list = Arrays.asList("xuxiaoxiao", "xudada", "xuzhongzhong");
list.forEach(value -> System.out.println(value));
}
/* 输出:
* xuxiaoxiao
* xudada
* xuzhongzhong
*/
}
2、分类
类别 | 使用形式 |
---|---|
静态方法引用 | 类名 :: 静态方法名 |
实例方法引用 | 对象名(引用名) :: 实例方法名 |
类方法引用 | 类名 :: 实例方法名 |
构造方法引用 | 类名 :: new |
(1)静态方法引用
public class Apple { private String name;
private String color;
private double weight; public Apple(String name, String color, double weight) {
this.name = name;
this.color = color;
this.weight = weight;
} public static int compareByWeight(Apple a1, Apple a2) {
double diff = a1.getWeight() - a2.getWeight();
return new Double(diff).intValue();
} //还有getter setter toString
}
有一个苹果的List,现在需要根据苹果的重量进行排序。List 的 sort 函数接收一个 Comparator 类型的参数,Comparator 是一个函数式接口,接收两个参数,
返回一个int值。Apple的静态方法compareByWeight正好符合Comparator函数式接口,所以可以使用:
Apple::compareByWeight 静态方法引用来替代lambda表达式
public class LambdaTest { public static void main(String[] args) { Apple apple1 = new Apple("红富士", "Red", 280);
Apple apple2 = new Apple("冯心", "Yello", 470);
Apple apple3 = new Apple("大牛", "Red", 320);
Apple apple4 = new Apple("小小", "Green", 300); List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4); //lambda 表达式形式
//appleList.sort((Apple a1, Apple a2) -> {
// return new Double(a1.getWeight() - a2.getWeight()).intValue();
//}); //静态方法引用形式(可以看出引用方法比上面的更加简单
appleList.sort(Apple::compareByWeight); appleList.forEach(apple -> System.out.println(apple)); }
}
输出:
Apple{category='红富士', color='Red', weight=280.0}
Apple{category='小小', color='Green', weight=300.0}
Apple{category='大牛', color='Red', weight=320.0}
Apple{category='冯心', color='Yello', weight=470.0}
注意:Apple.compareByWeight是方法的调用,而Apple::compareByWeight方法引用,这两者完全不是一回事。
(2)实例方法引用
这个compareByWeight是一个实例方法
public class AppleComparator { public int compareByWeight(Apple a1, Apple a2) {
double diff = a1.getWeight() - a2.getWeight();
return new Double(diff).intValue();
}
}
下面的例子通过实例对象的方法引用 comparator::compareByWeight 来代替lambda表达式
public class LambdaTest { public static void main(String[] args) { Apple apple1 = new Apple("红富士", "Red", 280);
Apple apple2 = new Apple("冯心", "Yello", 470);
Apple apple3 = new Apple("哈哈", "Red", 320);
Apple apple4 = new Apple("小小", "Green", 300); List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4); //lambda 表达式形式
//appleList.sort((Apple a1, Apple a2) -> {
// return new Double(a1.getWeight() - a2.getWeight()).intValue();
//}); //实例方法引用
AppleComparator comparator = new AppleComparator();
appleList.sort(comparator::compareByWeight); appleList.forEach(apple -> System.out.println(apple)); }
}
输出:
Apple{category='红富士', color='Red', weight=280.0}
Apple{category='小小', color='Green', weight=300.0}
Apple{category='哈哈', color='Red', weight=320.0}
Apple{category='冯心', color='Yello', weight=470.0}
通过上面两个例子可以看到,静态方法引用和实例方法引用都是比较好理解的。
(3)类方法引用
一般来说,同类型对象的比较,应该当前调用方法的对象与另外一个对象进行比较,好的设计应该像下面:
public class Apple { private String category;
private String color;
private double weight; public Apple(String category, String color, double weight) {
this.category = category;
this.color = color;
this.weight = weight;
}
//这里和上面静态方式唯一区别就是这个参数就一个,需要实例对象调这个方法
public int compareByWeight(Apple other) {
double diff = this.getWeight() - other.getWeight();
return new Double(diff).intValue();
} //getter setter toString
}
还是之前List排序的例子,看看使用类方法引用如何写:
public class LambdaTest { public static void main(String[] args) { Apple apple1 = new Apple("红富士", "Red", 280);
Apple apple2 = new Apple("黄元帅", "Yello", 470);
Apple apple3 = new Apple("红将军", "Red", 320);
Apple apple4 = new Apple("国光", "Green", 300); List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4); //lambda 表达式形式
//appleList.sort((Apple a1, Apple a2) -> {
// return new Double(a1.getWeight() - a2.getWeight()).intValue();
//}); //这里是类方法引用
appleList.sort(Apple::compareByWeight); appleList.forEach(apple -> System.out.println(apple)); }
}
输出:
Apple{category='红富士', color='Red', weight=280.0}
Apple{category='国光', color='Green', weight=300.0}
Apple{category='红将军', color='Red', weight=320.0}
Apple{category='黄元帅', color='Yello', weight=470.0}
这里使用的是:类名::实例方法名。首先要说明的是,方法引用不是方法调用。compareByWeight一定是某个实例调用的,就是lambda表达式的第一个参数,然后lambda
表达式剩下的参数作为 compareByWeight的参数,这样compareByWeight正好符合lambda表达式的定义。
或者也可以这样理解:
(Apple a1, Apple a2) -> { return new Double(a1.getWeight() - a2.getWeight()).intValue(); }
int compareByWeight(Apple other) 需要当前对象调用,然后与另外一个对象比较,并且返回一个int值。可以理解为lambda表达式的第一个参数 a1 赋值给当前对象, 然后 a2
赋值给 other对象,然后返回int值。
(4)构造方法引用
public class ConstructionMethodTest { public String getString(Supplier<String> supplier) {
return supplier.get();
} public static void main(String[] args) { ConstructionMethodTest test = new ConstructionMethodTest(); //lambda表达式形式
System.out.println(test.getString(() -> { return new String();})); //构造方法引用形式
System.out.println(test.getString(String::new)); }
}
getString 方法接收一个Supplier类型的参数,Supplier 不接收参数,返回一个String。lambda表达式应该这样写:
() -> { return new String();}
替换成方法引用的形式如下: 实际上调用的是String 无参构造方法
String::new
java代码(1)---Java8 Lambda的更多相关文章
- Java学习笔记--Java8 Lambda表达式
Java Lambda表达式入门:http://blog.csdn.net/renfufei/article/details/24600507 lambda内容的介绍:http://swiftlet. ...
- JAVA8 Lambda初体验
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.u ...
- 【Java学习笔记之三十一】详解Java8 lambda表达式
Java 8 发布日期是2014年3月18日,这次开创性的发布在Java社区引发了不少讨论,并让大家感到激动.特性之一便是随同发布的lambda表达式,它将允许我们将行为传到函数里.在Java 8之前 ...
- java代码之美(10)---Java8 Map中的computeIfAbsent方法
Map中的computeIfAbsent方法 Map接口的实现类如HashMap,ConcurrentHashMap,HashTable等继承了此方法,通过此方法可以在特定需求下,让你的代码更加简洁. ...
- java代码之美(14)---Java8 函数式接口
Java8 函数式接口 之前写了有关JDK8的Lambda表达式:java代码之美(1)---Java8 Lambda 函数式接口可以理解就是为Lambda服务的,它们组合在一起可以让你的代码看去更加 ...
- java代码之美(15)---Java8 Function、Consumer、Supplier
Java8 Function.Consumer.Supplier 有关JDK8新特性之前写了三篇博客: 1.java代码之美(1)---Java8 Lambda 2.java代码之美(2)---Jav ...
- java代码(15) ---java8 Function 、Consumer 、Supplier
Java8 Function.Consumer.Supplier 有关JDK8新特性之前还有三篇博客: 1,java代码(1)---Java8 Lambda 2,java代码(2)---Java8 S ...
- java代码(14) --Java8函数式接口
Java8函数式接口 之前有关JDK8的Lambda表达式 Java代码(1)--Java8 Lambda 函数式接口可以理解就是为Lambda服务的,它们组合在一起可以让你的代码看去更加简洁 一.概 ...
- java代码(10) ---Java8 Map中的computeIfAbsent方法
Map中的computeIfAbsent方法 一.案例说明 1.概述 在JAVA8的Map接口中,增加了一个computeIfAbsent,此方法签名如下: public V computeIfAbs ...
- Java8 Lambda表达式和流操作如何让你的代码变慢5倍
原文出处:ImportNew 有许许多多关于 Java 8 中流效率的讨论,但根据 Alex Zhitnitsky 的测试结果显示:坚持使用传统的 Java 编程风格——iterator 和 for- ...
随机推荐
- ipad4密码忘记锁定了如何破解
ipad4更新后被要求输入密码,但很长一段时间后忘记了,一直想不起来,也没有忘记密码的选项,以下是简单的破解方法. 注意:没有备份的资料是要被清空的 一.windows10系统,安装iTunes安装 ...
- Lottery
0x01 修改金币到8位,才能买东西 robots.txt中发现.git泄露 下载附件,得到源码 审计api.php 我们传入的值与随机生成的值进行比较, 按照相同的个数,得到不同的钱 if($num ...
- 力扣题解-面试题10- II. 青蛙跳台阶问题
题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶.求该青蛙跳上一个 n 级的台阶总共有多少种跳法. 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008, ...
- ql的python学习之路-day8
前言:本节主要学习的是函数的全局变量和局部变量以及递归 一.全局变量和局部变量 定义在函数外并且在函数头部的变量,叫做全局变量,全局变量在整个代码中都生效. 局部变量只在函数里生效,这个函数就叫做这个 ...
- Jenkins 插件 Role Strategy Plugin 使用
Manage and Assign Roles 1. Manage Roles Global Role 在此处,我们划分了四种权限,分别为: admin:超级管理员角色,管理整个服务: devops: ...
- 视口viewport
一.viewport 1. 何为视口? 视口是浏览器显示网页的矩形区域. 2. 默认视口:模拟一个大约1000像素宽的视口. 理想视口:因设备.操作系统.浏览器而异,一般而言,手机宽带大约在300-5 ...
- 论文阅读:Reducing Transformer Depth On Demand With Structured Dropout
Introduction 这篇paper是做Transformer压缩的,但其实bert的核心也就是transformer,这篇paper的实验里也做了bert的压缩.作者的主要工作是提出了Layer ...
- HDU3829 Cat VS Dog
题目链接:https://vjudge.net/problem/HDU-3829 题目大意: 有\(P\)个小孩,\(N\)只猫,\(M\)只狗.每个小孩都有自己喜欢的某一只宠物和讨厌的某一只宠物(其 ...
- win-sudo插件解决Git bash 执行脚本报错问题 bash: sudo: command not found
Windows git bash 默认没有sudo命令,可以添加win-sudo插件实现该功能 curl -s https://raw.githubusercontent.com/imachug/wi ...
- [JavaWeb基础] 032.第三方插件pinyin4j的使用
突然发现了一个比较新奇的插件,就是可以把我们输入的汉字,输出它所有的拼音的jar包.下面以代码的形式简单的介绍下这个插件 package com.babybus.sdteam.pinyin4j; im ...