一、Lambda 表达式
1.1简介
我认为,超过 3 行的逻辑就不适用 Lambda 表达式了。虽然看着很先进,其实 Lambda 表达式的本质只是一个 “语法糖”,由编译器推断并帮你转换包装为常规的代码,因此你可以使用更少的代码来实现同样的功能。本人不建议乱用,因为这就和某些很高级的黑客写的代码一样简洁,难懂,难以调适,维护人员想骂娘。
如果想要使用 Lambda 表达式,那么表达式简写里面只能是接口,并且接口里面只有一个方法。
1.2 语法
Lambda 表达式的语法如下
# 表达式一
(parameters) -> expression
# 表达式二
(parameters) ->{ statements; }
1.3 示例
1.3.1 示例一
我们在创建线程并启动时可以使用匿名内部类的写法,如下:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我爱你");
}
}).start();
可以使用 Lambda 的表达式对其进行修改,修改后如下:
new Thread(() ->{
System.out.println("我爱你")
});
// 省略规则写法
new Thread(() -> System.out.println("我爱你"));
1.3.2 示例二
现有方法定义如下,其中是一个接口,先使用匿名内部类的写法调用该方法
public static int calculateNum(IntBinaryOperator operator){
int a = 10;
int b = 20;
return operator.applyAsInt(a,b);
}
public static void main(String[] args) {
int calculateNum = calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
System.out.println(calculateNum);
}
Lambda 的写法如下:
public static void main(String[] args) {
int calculateNum = calculateNum((int left, int right) -> {
return left + right;
});
System.out.println(calculateNum);
// 省略规则写法
calculateNum((left,right) -> left+right);
}
1.3.3 示例三
现有方法定义如下,其中 IntPredicate 是一个接口,先使用匿名内部类的写法调用该方法
public static void printNum(IntPredicate predicate){
int [] arr = {1,2,3,4,5,6,7,8,9,10};
for (int i:arr) {
if(predicate.test(i)){
System.out.println(i);
}
}
public static void main(String[] args) {
printNum(new IntPredicate() {
@Override
public boolean test(int value) {
return value%2 ==0;
}
});
}
Lambda 的写法如下:
public static void main(String[] args) {
printNum((int value) ->{
return value%2 == 0;
});
// 省略规则写法
printNum(value -> value%2 == 0);
}
1.3.4 示例四
现有方法定义如下,其中 Function 是一个接口。先使用匿名内部类的写法调用该方法
public static<R> R typeCpnver(Function<String,R> function){
String str = "12345";
R result = function.apply(str);
return result;
}
public static void main(String[] args) {
Integer i = typeCpnver(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.valueOf(s);
}
});
System.out.println(i);
}
Lambda 的写法如下:
public static void main(String[] args) {
Integer result = typeCpnver((String str) ->{
return Integer.valueOf(str);
});
System.out.println(result);
String result2 = typeCpnver((String str) -> {
return str + "12345";
});
System.out.println(result2);
// 省略规则写法
typeCpnver(str -> Integer.valueOf(str));
}
1.3.5 示例五
现有方法定义如下,其中 IntConsumer 是一个接口,先使用匿名内部类的写法调用该方法
public static void foreachArr(IntConsumer consumer){
int [] arr = {1,2,3,4,5,6,7,8,9,10};
for (int i:arr) {
consumer.accept(i);
}
}
public static void main(String[] args) {
foreachArr(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value%2==0);
}
});
}
Lambda 的写法如下:
public static void main(String[] args) {
foreachArr((int value) ->{
System.out.println(value%2==0);
});
// 省略规则写法
foreachArr(value -> System.out.println(value%2==0));
}
1.4 省略规则
1、参数类型可以省略
2、方法体只有一句代码时大括号、return 和唯一一句代码的分号可以省略
3、方法只有一个参数时小括号可以省略。
二、Stream 流
2.1 概述
Java8 的 Stream 使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。
2.2 案例数据准备
首先创建一个 Author 类,代码如下:
@Data
@NoArgsConstructor
@AllArgsConstructor
// 相当于重写了 equals 方法
@EqualsAndHashCode
public class Author {
private Long id;
private String name;
// 姓名
private Integer age;
// 简介
private String intro;
// 作品
private List<Book> books;
}
然后创建一个 Book 类,代码如下:
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode // 用于后期去重使用
public class Book {
private Long id;
// 书名
private String name;
// 分类
private String category;// "哲学,小说"
// 评分
private Integer score;
// 简介
private String intro;
}
构建数据的类的代码如下:
public class StreamDemo {
private static List<Author> getAuthors() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
Author author2 = new Author(2L,"亚拉索",15,"狂风也追逐不上他的思考速度",null);
Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
Author author4 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
//书籍列表
List<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();
books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));
books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);
List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
return authorList;
}
}
2.3 快速入门
2.3.1 需求
我们可以调用 getAuthors 方法获取作家的集合,现在需要打印所有年龄小于 18 的作家的名字,并且要注意去重。
2.3.2 实现
public static void main(String[] args) {
List<Author> authorList = getAuthors();
authorList
.stream() // 将集合转换成流
.distinct() // 去重
.filter(author -> author.getAge()<18) // 筛选年龄小于 18
.forEach(author -> System.out.println(author.getName())); // 遍历打印名字
}
2.4 常用操作
2.4.1 创建流
单列集合:集合对象.stream()
List<Author> authorList = getAuthors();
Stream<Author> stream = authorList.stream();
数组:Arrays.stream() 或者使用 Stream.of 来创建
Integer [] arr = {1,2,3,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream1 = Stream.of(arr);
双列集合:转换成单列集合再创建
Map<String,Object> map = new HashMap<>();
map.put("年龄",12);
map.put("学号",12345);
map.put("身高",170);
Stream<Map.Entry<String, Object>> stream = map.entrySet().stream();
2.4.2 中间操作
2.4.2.1 filter
可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
// 打印所有姓名长度大于1的作家的姓名
public void test1(){
getAuthors().stream()
.filter(author -> author.getName().length()>1)
.forEach(author -> System.out.println(author.getName()));
}
2.4.2.2 map
可以把流中的元素进行计算或转换
// 打印所有作家的名称
public static void test2(){
getAuthors().stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
}
// 将所有作家的年龄加10,然后打印年龄
public static void test3(){
getAuthors().stream()
.map(author -> author.getAge()+10)
.forEach(age -> System.out.println(age));
}
2.4.2.3 distinct
可以去重流种的重复元素,需要注意的是 distinct 方法依赖 Object 的 equals 方法来判断是否是相同的对象,所以需要注意重写 equals 方法
// 打印所有作家的名字,并且要求不能有重复元素
public static void test4(){
getAuthors().stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
}
2.4.2.4 sorted
可以对流中的元素进行排序,注意,如果调用了空参的 sorted() 方法,需要流中的元素实现 Comparable 接口。
// 对流中的元素按照年龄进行降序排列,并且要求不能有重复的元素
public static void test5(){
getAuthors().stream()
.distinct()
.sorted((a,b) -> b.getAge().compareTo(a.getAge()))
.forEach(author -> System.out.println(author.getAge()));
}
2.4.2.5 limit
可以设置流的最大长度,超出的部分将被抛弃
// 对流中的元素按照年龄进行降序排列,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的名字
public static void test6(){
getAuthors().stream()
.distinct()
.sorted((a,b) -> b.getAge().compareTo(a.getAge()))
.limit(2)
.forEach(author -> System.out.println(author.getAge()));
}
2.4.2.6 skip
跳过流中的前 n 个元素,返回剩下的元素
// 打印除了年龄最大的作家以外的作家,要求不能有重复元素,并且按照年龄降序排列
public static void test7(){
getAuthors().stream()
.distinct()
.sorted((a,b) -> b.getAge()-a.getAge())
.skip(1)
.forEach(author -> System.out.println(author.getName()));
}
2.4.2.7 flatMap
map 只能把一个对象转换成另一个对象来作为流中的元素,而 flatMap 可以把一个对象转换成多个对象作为流中的元素。
// 打印所有书籍的名字。要求对重复的元素进行去重
public static void test8(){
getAuthors().stream()
.flatMap(author -> author.getBooks().stream())// 将其转换成 Book 流返回
.distinct()
.forEach(book -> System.out.println(book.getName()));
}
public static void test9(){
getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
// 对书籍去重
.distinct()
// 数组转换成 stream
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
// 对字段去重
.distinct()
.forEach(type -> System.out.println(type));
}
2.4.3 终结操作
2.4.3.1 foreach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历的元素进行什么遍历操作。
// 输出所有作家的名字
public static void test10(){
getAuthors().stream()
.forEach(author -> System.out.println(author.getName()));
}
2.4.3.2 count
可以用来获取当前流中元素的个数
// 打印这些作家的所出书籍的数目,注意删除重复元素
public static void test11(){
long count = getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
}
2.4.3.3 max&min
可以用来获取当前流中的最值
// 分别获取这些作家的所出书籍的最高分和最低分并打印
public static void test12(){
Optional<Integer> max = getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((b1, b2) -> b1 - b2);
System.out.println(max.get());
Optional<Integer> min = getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((b1, b2) -> b2 - b1);
System.out.println(min.get());
}
2.4.3.4 collect
把当前流转换成一个集合
// 获取一个存放所有作者名字的 List 集合
public static void test13(){
List<String> collect = getAuthors().stream()
.map(author -> author.getName())
.distinct()
.collect(Collectors.toList());
System.out.println(collect);
}
// 获取一个所有书名的 Set 集合
public static void test14(){
Set<String> collect = getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.distinct()
.collect(Collectors.toSet());
System.out.println(collect);
}
// 获取一个 map 集合,map 的key为作者名, value 为 List<Book>
public static void test15(){
Map<Object, Object> collect = getAuthors().stream()
.distinct()
.collect(Collectors.toMap(author ->author.getName(),author -> author.getBooks()));
System.out.println(collect);
}
// 按照 id 进行分组,相同 id 的元素放在一起
public static void main(String[] args) {
List<Author> authors = getAuthors();
Map<Long, List<Author>> collect = authors.stream().collect(Collectors.groupingBy(author -> author.getId()));
for (Map.Entry<Long, List<Author>> entry : collect.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
2.4.3.5 查找与匹配
anyMatch:用来判断是否有任意符合匹配条件的元素,结果为 boolean 类型
// 判断是否存在年龄在 29 以上的作家
public static void test16(){
boolean b = getAuthors().stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(b);
}
allMatch:可以用来判断是否都符合匹配条件,结果为 boolean 类型,如果都符合结果为 true,否则都返回 false。
// 判断是否所有的作家都是成年人
public static void test17(){
boolean b = getAuthors().stream()
.allMatch(author -> author.getAge() >= 18);
System.out.println(b);
}
noneMatch:可以判断流中的元素是否都不符合匹配条件,如果都不符合结果为 true,否则结果为 false。
// 判断作家是否都没有超过 100 岁的
public static void test18(){
boolean b = getAuthors().stream()
.noneMatch(author -> author.getAge() > 100);
System.out.println(b);
}
findAny:获取流中的任意一个元素,该方法没有办法保证获取的一定是流中的第一个元素。
// 获取任意一个大于 18 的作家,如果存在就输出他的名字
public static void test19(){
Optional<Author> any = getAuthors().stream()
.filter(author -> author.getAge() > 18)
.findAny();
any.ifPresent(author -> System.out.println(author.getName()));
}
findFirst:获取流中的第一个元素
// 获取一个年龄最小的作家,并输出他的姓名
public static void test20(){
Optional<Author> first = getAuthors().stream()
.sorted((a, b) -> a.getAge() - b.getAge())
.findFirst();
first.ifPresent(author -> System.out.println(author.getName()));
}
2.4.3.6 reduce 归并
对流中的数据按照你制定的计算方式计算出一个结果。
reduce 的作用是把 stream 种的元素给结合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和在初始值的基础上进行计算,计算结果再和后面的元素计算。
它内部的计算方式如下:
T result = identity;
for(T element: this stream)
result = accumulator.apply(result,element)
return result;
其中 identity 就是我们可以通过方法参数传入的初始值, accumulator 的 apply 具体进行什么计算也是通过我们方法参数来确定的。
// 使用 reduce 求所有作者年龄的和
public static void test21(){
Integer reduce = getAuthors().stream()
.distinct()
.map(author -> author.getAge())
// 第一个参数为初始值,后面为计算方式
.reduce(0, (result1,result2) -> result1 + result2);
System.out.println(reduce);
}
// 使用 reduce 求所有作者种年龄的最大值
public static void test22(){
Integer reduce = getAuthors().stream()
.distinct()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, (result, result2) -> result > result2 ? result : result2);
System.out.println(reduce);
}
// 使用 reduce 求所有作者种年龄的最小值
public static void test23(){
Integer reduce = getAuthors().stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (result, result2) -> result > result2 ? result2 : result);
System.out.println(reduce);
}
2.5 注意事项
1、惰性求值(如果没有终结操作,中间操作是不会得到执行的)
2、流是一次性的(一旦一个流对象经过一个终结操作,这个流就不能再被使用)
3、不会影响原数据(我们在流中可以对数据做很多处理,但是正常情况下是不会影响原来集合种的元素,这往往也是我们期望的)
三、方法引用
我们在使用 Lambda 时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。
3.1 基本用法
我们在使用 Lambda 时不需要考虑什么使用可以使用方法引用,用哪种方法引用,方法的格式是什么,我们只需要在写完 Lambda 方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。
当我们方法引用使用的多了慢慢的也可以直接写出方法引用。
3.2 基本格式
类名或者对象名::方法名
3.3 语法详情
3.3.1 引用静态方法
其实就是引用类的静态方法,语法如下:
类名::方法名
使用前提:如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。
例如:如下的代码就可以用方法引用进行简化
public static void test24(){
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.map(author -> author.getAge())
.map(age -> String.valueOf(age));
}
注意:如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。
优化后的代码如下:
public static void test24(){
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.map(author -> author.getAge())
.map(String::valueOf);
}
3.3.2 引用对象的实例方法
语法如下:
对象名::方法名
使用前提:如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。
例如:如下的代码就可以进行简化
public static void test24(){
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
StringBuilder sb = new StringBuilder();
stream.map(author -> author.getName())
.forEach(name -> sb.append(name));
}
优化后的代码如下:
public static void test24(){
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
StringBuilder sb = new StringBuilder();
stream.map(author -> author.getName())
.forEach(sb::append);
}
3.3.3 引用类的实例方法
语法如下:
类名::方法名
使用前提:如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。
例如:如下的代码就可以进行简化
interface UserString{
String use(String str,int start,int end);
}
public static String subAuthorName(String str, UserString userString){
int start = 0;
int length =1;
return userString.use(str,start,length);
}
public static void main(String[] args) {
subAuthorName("我爱你老铁", new UserString() {
@Override
public String use(String str, int start, int end) {
return str.substring(start,end);
}
});
}
优化后的代码如下:
public static void main(String[] args) {
subAuthorName("我爱你老铁", String::substring);
}
3.3.4 构造器引用
如果方法体中的一行代码是构造器的话就可以使用构造器引用。
语法如下:
类名::new
使用前提:如果我们在重写方法的时候,方法体只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。
例如:如下的代码就可以进行简化
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(name -> new StringBuilder(name))
.map(sb -> sb.append("我爱你").toString())
.forEach(str -> System.out.println(str));
}
优化后的代码如下:
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.map(Author::getName)
.map(StringBuilder::new)
.map(sb -> sb.append("我爱你").toString())
.forEach(str -> System.out.println(str));
}
四、高级用法
4.1 基本数据类型优化
我们之前用到的很多 Stream 的方法都使用了泛型,所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是它们的包装类。JDK5 引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很小。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
所以为了让我们能够对这部分的时间消耗进行优化。Stream 还提供了很多专门针对基本数据类型的方法。
例如:mapToInt、mapToLong、mapToDouble、floatMapToInt、floatMapToDouble 等。
例如:如下的代码就可以进行优化
public static void main(String[] args) {
List<Author> authors = getAuthors();
// 我们的 age 类型为 Integer 类型,下面的+操作,会自动进行拆箱和装箱操作
authors.stream()
.map(author -> author.getAge())
.map(age -> age+10)
.filter(age -> age>18)
.map(age -> age+2)
.forEach(System.out::println);
}
优化后的代码如下:
public static void main(String[] args) {
List<Author> authors = getAuthors();
// 我们的 age 类型为 Integer 类型,下面的+操作,会自动进行拆箱和装箱操作
authors.stream()
.mapToInt(author -> author.getAge())
.map(age -> age+10)
.filter(age -> age>18)
.map(age -> age+2)
.forEach(System.out::println);
}
4.2 并行流
当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完成,如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解和认识,而如果我们使用 Stream 的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。
例如:如下的代码就可以使用并行流处理。
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = stream.filter(num -> num > 5)
.reduce((a, b) -> a + b)
.get();
System.out.println(sum);
}
第一种转换成并行流的方式,直接调用 stream 的 parallel() 方法。
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 只需要调用 parallerl() 方法即可,就是多线程执行了
Integer sum = stream.parallel()
.filter(num -> num > 5)
.reduce((a, b) -> a + b)
.get();
System.out.println(sum);
}
第二种转换成并行流的方式,直接调用集合的 parallelStream() 方法。
public static void test24() {
List<Author> authors = getAuthors();
// 直接调用 parallelStream 方法即可
Stream<Author> stream = authors.parallelStream();
StringBuilder sb = new StringBuilder();
stream.map(author -> author.getName())
.forEach(sb::append);
}
我们可以调用 peek() 方法进行调试,他是个中间操作,不会结束流,代码如下:
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 只需要调用 parallerl() 方法即可,就是多线程执行了
Integer sum = stream.parallel()
.peek(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println("线程名称:"+Thread.currentThread().getName()+" 处理的数据为:"+integer);
}
})
.filter(num -> num > 5)
.reduce((a, b) -> a + b)
.get();
System.out.println(sum);
}