Lambda表达式&Stream流-函数式编程
字数: 0 字 时长: 0 分钟
1.概述
字数: 0 字 时长: 0 分钟
1.1 为什么学?
能够看懂公司代码
大数据量下处理集合效率高
代码可读性高
消灭嵌套地狱
这是没有用函数式编程写的代码
这是函数式编程写的代码
1.2 函数式编程思想
1.2.1 概念
面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对教据进行了什么操作
比如有一个带参的方法、参数是我们要操作的数据、具体对数据进行了什么操作、主要关心这两个方面
1.2.2 优点
- 代码简洁 开发快速
- 接近自然语言,易于理解
- 易于“并发编程”
2.lambda 表达式
字数: 0 字 时长: 0 分钟
2.1 概述
Lambda是JDK8(2014 年发布)中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。
不是所有的匿名内部类都可以使用 lambda 表达式
2.2 核心原则
可推导可省略
如果一些参数的类型可以被推导出来、就可以省略不写 方法名可以被推导、就可以省略方法名
2.3 基本格式
(参数列表)->{代码}
练习一
//老写法
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("我是老写法");
}
}).start();
简化前提:
如果匿名内部类是一个接口、并且重写方法只有一个的时候
lambda 关注的是什么:只关注参数和方法体
() {System.out.println("我是老写法");}
简化后
new Thread(() ->{System.out.println("我是新写法")}).start();
// 参数 方法体
练习二
现有方法定义如下,其中IntBinaryOperator是一个接口。先使用匿名内部类的写法调用该方法。
public static int calculateNum(IntBinaryOperator operator){
int a= 10;
int b = 20;
return operator.applyAsInt(a, b);
}
public static void main(String[] args){
calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
}
lambda 写法
只关注参数和具体执行代码 参数和操作代码之间加一个 ->
calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt
//只留下这些 + 一个 ->
(int left, int right) {
return left + right;
}
//
});
//实现效果
calculateNum((int left, int right) -> {
return left + right;
});
练习三
现有方法定义如下,其中IntPredicate是一个接口。先使用匿名内部类的写法调用该方法。
public static void main(String[] args) {
printNum(new IntPredicate() {
@Override
public boolean test(int value) {
return value%2 == 0;
}
});
}
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);
}
}
}
改造后
printNum((int value) -> {
return value%2 == 0;
});
练习四
现有方法定义如下,其中Function是一个接口。先使用匿名内部类的写法调用该方法。
public static void main(String[] args) {
Integer integer = typeConver(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.valueOf(s);
}
});
System.out.println(integer);
}
public static <R>R typeConver(Function<String,R> function){
String str ="1235";
R result = function.apply(str);
return result;
}
}
转换后
Integer integer2 = typeConver((String s) ->{
return Integer.valueOf(s);
});
String str = typeConver(new Function<String, String>() {
@Override
public String apply(String s) {
return s + "哈哈";
}
});
System.out.println(str);
String str2 = typeConver((String s) ->{
return s + "哈哈";
});
练习五
现有方法定义如下,其中Intconsumer是一个接口。先使用匿名内部类的写法调用该方法。
public static void main(String[] args) {
foreachArr(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
}
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);
}
}
转换后
foreachArr((int value) ->{
System.out.println(value);
});
2.4 省略规则
参数类型可以省略
javaforeachArr((value) ->{ System.out.println(value); });
方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
javaforeachArr((value) -> System.out.println(value) );
方法只有一个参数时小括号可以省略
javaforeachArr(value -> System.out.println(value) );
以上这些规则都记不住也可以省略不记
3.Stream流
字数: 0 字 时长: 0 分钟
3.1概述
Java8的stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们 对集合或数组操作。
3.2 案例数据准备
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author {
//id
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
//id
private Long id;
//书名
private String name;
//分类
private String category;
//评分
private Integer score;
//简介
private String intro;
}
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;
}
3.3 快速入门
3.3.1 需求
我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重
3.3.2 实现
List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.filter(new Predicate<Author>() { //过滤小于18的
@Override
public boolean test(Author author) {
return author.getAge() < 18;
}
})
.forEach(new Consumer<Author>() { //获取人名
@Override
public void accept(Author author) {
System.out.println(author.getName());
}
});
}
优化后
authors.stream()
.distinct() //去重
.filter(author -> author.getAge() < 18)
.forEach(author -> System.out.println(author.getName()));
3.4 常用操作
3.4.1 创建流
单列集合: 集合对象.stream()
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream
数组:Arrays.stream(数组)
或者使用Stream.of
来创建
Integer[] arr = {1,2,3,4,5};
//第一种
Stream<Integer> stream = Arrays.stream(arr);
//第二种
Stream<Integer> stream2 = Stream.of(arr);
双列集合:转换成单列集合后再创建
List<Author> authors = getAuthors();
Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);
map.put("黑子",17);
map.put("日向翔阳",16);
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
Stream<Map.Entry<String, Integer>> stream = entrySet.stream();
stream
.distinct()
.filter(stringIntegerEntry -> stringIntegerEntry.getValue() > 16)
.forEach(stringIntegerEntry -> System.out.println(stringIntegerEntry));
3.4.2 中间操作
filter
可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
List<Author> authors = getAuthors();
//打印所有姓名长度大于1的作家的姓名
authors.stream()
.filter(author -> author.getName().length() > 1) //判断名字大于1
.forEach(author -> System.out.println(author.getName()));
map
可以把对流中的元素进行计算或转换。
转换
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName()) //把对象转换成了String
.forEach(s -> System.out.println(s));
计算
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.forEach(age -> System.out.println(age));
distinct
可以去除流中的重复元素。
例如:
打印所有作家的姓名,并且要求其中不能有重复元素。
注意:distinct方法是依赖0bject的equals方法来判断是否是相同对象的。所以需要注意重新equals方法.
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
sorted
可以对流中的元素进行排序
例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复元素
首先了解
sorted()方法有两种重载形式 空参和有参
有参:
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted((o1, o2) -> o1.getAge().compareTo(o2.getAge()))
.forEach(author -> System.out.println(author));
无参:
//先在实体类实现Comparable接口
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Author implements Comparable<Author>{
//id
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books;
@Override
public int compareTo(Author o) {
return this.age - o.getAge();
}
}
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted()
.forEach(author -> System.out.println(author.getAge()));
limit
可以设置流的最大长度,超出的部分将被抛弃。
例如:
对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted((Author o1, Author o2) ->
o2.getAge() - o1.getAge())
.limit(2)
.forEach((Author author) ->
System.out.println(author.getName())
);
skip
跳过流中的前n个元素,返回剩下的元素
例如:
打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted((Author o1, Author o2) ->
o2.getAge() - o1.getAge()
)
.skip(1)
.forEach(author -> System.out.println(author.getName()));
flatMap
map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
例一:
打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
完整的flatMap代码
List<Author> authors = getAuthors();
authors.stream()
.flatMap(new Function<Author, Stream<Book>>() {
@Override
public Stream<Book> apply(Author author) {
return author.getBooks().stream();
}
})
.distinct()
.forEach(new Consumer<Book>() {
@Override
public void accept(Book book) {
System.out.println(book.getName());
}
});
例二:
打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(category -> System.out.println(category));
3.4.3 终结操作
forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
例子:
输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.distinct()
.forEach(name -> System.out.println(name));
count
可以用来获取当前流中元素的个数。
例子:
打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();
long count = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
max&min
可以用来或者流中的最值。
例子:
分别获取这些作家的所出书籍的最高分和最低分并打印。
最高分
List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((o1, o2) -> o1 - o2);
System.out.println(max.get());
最低分
List<Author> authors = getAuthors();
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((o1, o2) -> o1 - o2);
System.out.println(min.get());
collect
把当前流转化为一个集合。
例子1:获取一个存放所有作者名字的List集合
javaList<Author> authors = getAuthors(); List<String> collect = authors.stream() .map(author -> author.getName()) .collect(Collectors.toList()); System.out.println(collect);
例子2:获取一个所有书名的Set集合
javaList<Author> authors = getAuthors(); Set<String> collect1 = authors.stream() .flatMap(author -> author.getBooks().stream()) .map(book -> book.getName()) .collect(Collectors.toSet()); System.out.println(collect1);
例子3:获取一个map集合,map的key为作者名,value为List
javaList<Author> authors = getAuthors(); Map<String, List<Book>> collect2 = authors.stream() .collect(Collectors.toMap(new Function<Author, String>() { @Override public String apply(Author author) { return author.getName(); } }, new Function<Author, List<Book>>() { @Override public List<Book> apply(Author author) { return author.getBooks(); } }));
简化后
javaList<Author> authors = getAuthors(); Map<String, List<Book>> collect2 = authors.stream() .distinct() .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks())); System.out.println(collect2);
使用toMap()函数之后,返回的就是一个Map了,自然会需要key和value。 toMap()的第一个参数就是用来生成key值的,
第二个参数就是用来生成value值的。
第三个参数用在key值冲突的情况下:如果新元素产生的key在Map中已经出现过了,第三个参数就会定义解决的办法。
查找和匹配
anyMatch
- 可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
- 例子:判断是否有年龄在29以上的作家
- 只要有一个作家是 29 岁以上的结果为 true
List<Author> authors = getAuthors();
boolean b = authors.stream()
.anyMatch(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 29;
}
});
System.out.println(b);
简化后
List<Author> authors = getAuthors();
boolean b1 = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(b1);
allMatch
可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
例子:判断是否所有的作家都是成年人
所有的作家都是 > 18 都是成年才才返回 true
javList<Author> authors = getAuthors(); boolean b1 = authors.stream() .allMatch(new Predicate<Author>() { @Override public boolean test(Author author) { return author.getAge() > 18; } }); System.out.println(b1);
简化后
List<Author> authors = getAuthors();
boolean b = authors.stream()
.allMatch(author -> author.getAge() > 18);
System.out.println(b);
noneMatch
- 可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false。
- 例子:判断作家是否都没有超过100岁
List<Author> authors = getAuthors();
boolean b = authors.stream()
.noneMatch(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 100;
}
});
System.out.println(b);
//简化后
List<Author> authors = getAuthors();
boolean b1 = authors.stream()
.noneMatch(author -> author.getAge() > 100);
System.out.println(b1);
findAny
- 获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
- 例子:获取任意一个年龄大于18的作家,如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> any1 = authors.stream()
.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 18;
}
})
.findAny();
any1.ifPresent(new Consumer<Author>() {
@Override
public void accept(Author author) {
System.out.println(author.getName());
}
});
简化后
List<Author> authors = getAuthors();
Optional<Author> any = authors.stream()
.filter(author -> author.getAge() > 18)
.findAny();
any.ifPresent(author -> System.out.println(author.getName()));
findFirst
- 获取流中的第一个元素。
- 例子:获取一个年龄最小的作家,并输出他的姓名。
Optional<Author> first1 = authors.stream()
.sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
.findFirst();
first1.ifPresent(f -> System.out.println(f.getName()));
简化后
List<Author> authors = getAuthors();
Optional<Author> first = authors.stream()
.sorted((o1, o2) -> o1.getAge().compareTo(o2.getAge()))
.findFirst();
first.ifPresent(f -> System.out.println(f.getName()));
reduce归并
- 对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)
- reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次的拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
reduce俩个参数的重载形式
reduce俩个参数的重载形式内部的计算方式如下:
T result = identity;
for(T element : this stream)
result = accumulator.apply(result,element)
return result;
类似这个样子
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int result = 0; // 0 类似 identity
for (int i : arr) {
result = result + i;
}
System.out.println(result);
- 其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
例子1:使用reduce求所有作者年龄的和
List<Author> authors = getAuthors();
Integer reduce = authors.stream()
.map(author -> author.getAge())
.reduce(0, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result + element;
}
});
System.out.println(reduce);
简化后
List<Author> authors = getAuthors();
Integer reduce1 = authors.stream()
.map(author -> author.getAge())
.reduce(0, (a, b) -> a + b);
System.out.println(reduce1);
例子2:使用reduce求所有作者中年龄的最大值。
Integer reduce = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result < element ? element : result;
}
});
System.out.println(reduce);
//简化后
List<Author> authors = getAuthors();
Integer reduce = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
System.out.println(reduce);
例子3:使用reduce求所有作者中年龄的最小值。
Integer reduce = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result > element ? element : result;
}
});
System.out.println(reduce);
//简化后
List<Author> authors = getAuthors();
Integer reduce = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (result ,element) -> result > element ? element : result);
System.out.println(reduce);
reduce一个参数的重载形式
boolean foundAny = false;
T result = null;
for (T element : this stream) {
if (!foundAny) {
foundAny = true;
result = element;
}
else
result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();
内部原理类似以上
用一个参数的重载形式求年龄最小值
List<Author> authors = getAuthors();
Optional<Integer> reduce = authors.stream()
.map(author -> author.getAge())
.reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer element) {
return result < element ? result : element;
}
});
reduce.ifPresent(age -> System.out.println(age));
//简化后
List<Author> authors = getAuthors();
Optional<Integer> reduce = authors.stream()
.map(author -> author.getAge())
.reduce((result, element) -> result < element ? result : element);
reduce.ifPresent(age -> System.out.println(age));
3.5 注意事项
- 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
- 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
- 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们所期望的)
出处。
4.Optional
字数: 0 字 时长: 0 分钟
4.1 概述
我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。
例如:
Author author = getAuthor();
if(author != null){
System.out.println(author.getName());
}
尤其是对象中的属性还是一个对象的情况下。这种判断会更多。
而过多的判断语句会让我们的代码显得臃肿不堪。
所以在JDK8中引入了optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。
并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。
4.2 使用
4.2.1 创建对象
Optional就好像是包装类,可以把我们的具体数据封装0ptional对象内部。然后我们去使用0ptional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。
我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为nul都不会出现问题
public class OptionalDemo1 {
public static void main(String[] args) {
Author authors = getAuthors();
Optional<Author> optionalAuthor = Optional.ofNullable(authors);
optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
}
private static Author getAuthors() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return null;
}
}
这样也不会出现空指针异常的
但是
你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法,让其的返回值就是封装好的0ptional的话,我们在使用时就会方便很多。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.ifPresent(author -> System.out.println(author.getName()));
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
改造这个方法后、显得简单很多了
而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回,封装的过程也不需要我们自己操作。
以下方法不是特别常用、也不建议在开发中使用
第一: of()
如果你确定一个对象不是空的则可以使用0ptional的静态方法of来把数据封装成Optional对象。
public static void main(String[] args) {
Author authors = getAuthors();
Optional<Author> optionalAuthor = Optional.of(authors);
optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
}
private static Author getAuthors() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return null;
}
但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)
结果如下:
其实这个方法有点脱裤子放屁了、我都确定不为 null了、我还用 Optional 干嘛
原理我们打开ofNullable源码
value 是传入的值、看到return 的三元表达式了吗
如果是空返回一个 empty() 不为空才调用 of() 方法
第二:empty()
如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为nul,这个时候就需要把nul封装成 Optional对象返回。这时则可以使用optional的静态方法empty来进行封装。
private static Optional<Author> getAuthorsOptiona2() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return author == null ? Optional.empty() : Optional.of(author);
}
看了第二个方法、我的建议还是 用 ofNullable()
4.2.2 安全消费值
我们获取到一个0ptional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。
这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。
例如,以下写法就优雅的避免了空指针异常。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.ifPresent(author -> System.out.println(author.getName()));
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
4.2.3 获取值
如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。因为当Optional内部的数据为空的时候会出现异常
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
Author author1 = authorsOptiona.get();
System.out.println(author1);
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(null);
}
报错
4.2.4 安全的获取值
如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。
- orElseGet
获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返 回。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
Author author = authorsOptiona.orElseGet(new Supplier<Author>() {
@Override
public Author get() {
return new Author(); //返回的这个对象、就是当你这个数据为空返回的一个默认值
}
});
}
private static Optional<Author> getAuthorsOptiona() {
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(null);
}
//简化后
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
Author author = authorsOptiona.orElseGet(() -> new Author(1L,"锐雯",33,"一个从菜刀中明悟哲理的祖安人",null));
}
private static Optional<Author> getAuthorsOptiona() {
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(null);
}
如果 Optional 中是有值的、就返回值、没值就返回你所设置的值 以上列子、有值就返回蒙多、如果没有值就返回锐雯
- orElseThrow
获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
try {
Author author = authorsOptiona.orElseThrow(new Supplier<Throwable>() {
@Override
public Throwable get() {
return new RuntimeException("数据为空"); // 为空的时候抛出这个异常、你的 spring 同意异常处理就能捕获到
}
});
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(null);
}
//简化后
try {
Author author = authorsOptiona.orElseThrow(() -> new RuntimeException("数据为空"));
System.out.println(author);
} catch (Throwable e) {
throw new RuntimeException(e);
}
4.2.5 过滤
我们可以使用fiter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 18;
}
}).ifPresent(author1 -> System.out.println(author1.getName()));
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
//简化后
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.filter(author -> author.getAge() > 18).ifPresent(author1 -> System.out.println(author1.getName()));
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
4.2.6 判断
我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
if (authorsOptiona.isPresent()){
System.out.println(authorsOptiona.get().getName());
}
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
4.2.7 数据转换
Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。 例如我们想获取作家的书籍集合。
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.map(new Function<Author, List<Book>>() {
@Override
public List<Book> apply(Author author) {
return author.getBooks();
}
})
.ifPresent(new Consumer<List<Book>>() {
@Override
public void accept(List<Book> books) {
System.out.println(books);
}
});
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
简化后
public static void main(String[] args) {
Optional<Author> authorsOptiona = getAuthorsOptiona();
authorsOptiona.map(author -> author.getBooks())
.ifPresent(books -> System.out.println(books));
}
private static Optional<Author> getAuthorsOptiona() {
//数据初始化
Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
return Optional.ofNullable(author);
}
5.函数式接口
字数: 0 字 时长: 0 分钟
5.1 概述
- 只有一个抽象方法的接口我们称之为函数接口。
- JDK的函数式接口都加上了
@Functionallnterface
注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。
5.2 常见的函数式接口
Consumer消费接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。
Function计算转换接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回
- Predicate判断接口
- 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果
- Supplier生产型接口
- 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回
5.3 常用的默认方法
and
- 我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件例如:
- 例如:打印作家中年龄大于17并且姓名的长度大于1的作家。
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 17;
}
}.and(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getName().length() > 1;
}
})
);
//简化
stream.filter(((Predicate<Author>) author -> author.getAge() > 17).and(author -> author.getName().length() > 1));
printNum2(new IntPredicate() {
@Override
public boolean test(int value) {
return value % 2 == 0;
}
}, new IntPredicate() {
@Override
public boolean test(int value) {
return value > 4;
}
});
//简化后
printNum2(value -> value % 2 == 0, value -> value > 4);
public static void printNum2(IntPredicate predicate,IntPredicate predicate2){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
for( int i : arr ){
if(predicate.and(predicate2).test(i)){
System.out.println(i);
}
}
}
or
- 我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。例如:
- 例如:打印作家中年龄大于17或者姓名的长度小于2的作家。
public static void main(String[] args) {
//例如:打印作家中年龄大于17或者姓名的长度小于2的作家
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 17;
}
}.or(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getName().length() < 2;
}
}));
}
negate
- Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反
- 例如:打印作家中年龄不大于17的作家。
public static void main(String[] args) {
//例如:打印作家中年龄不大于17的作家。
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 17;
}
}.negate()).forEach(author -> System.out.println(author.getAge()));
}
6.方法引用
字数: 0 字 时长: 0 分钟
我们在使用lambda时,如果方法体中只有一个方法的调用的话(包括构造方法) ,我们可以用方法引用进一步简化代码。
6.1 推荐用法
- 我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。
6.2从基本格式
类名或者对象名::方法名
6.3 语法详解(了解)
6.3.1 引用类的静态方法
其实就是引用类的静态方法
格式
类名::方法名
使用前提
- 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。
例如:如下代码就可以用方法引用进行简化
authors.stream()
.map(new Function<Author, Integer>() {
@Override
public Integer apply(Author author) {
return author.getAge();
}
})
.map(new Function<Integer, String>() {
@Override
public String apply(Integer age) {
return String.valueOf(age);
}
});
//简写
authors.stream()
.map(author -> author.getAge())
.map(String::valueOf);
- 注意:如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。
6.3.2 引用对象的实例方法格式
格式
对象名::方法名
使用前提
- 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
.map(new Function<Author, String>() {
@Override
public String apply(Author author) {
return author.getName();
}
})
.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
sb.append(s);
}
});
//简化
authors.stream()
.map(author -> author.getName())
.forEach(sb::append);
6.3.3 引用类的实例方法
格式
类名::方法名
使用前提
- 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。
interface UseString{
String use(String str,int start,int length);
}
public static String subAuthorName(String str,UseString useString){
int start = 0;
int length = 1;
return useString.use(str,start,length);
}
public static void main(String[] args) {
subAuthorName("kerwim", new UseString() {
@Override
public String use(String str, int start, int length) {
return str.substring(start,length);
}
});
//简化后
subAuthorName("kerwim", String::substring);
}
6.3.4 构造器引用
如果方法体中的一行代码是构造器的话就可以使用构造器引用。
格式
类名::new
使用前提
- 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(name ->new StringBuilder(name))
.map(sb->sb.append("-kerwim").toString())
.forEach(str -> System.out.println(str));
authors.stream()
.map(author -> author.getName())
.map(StringBuilder::new)
.map(sb->sb.append("-kerwim").toString())
.forEach(str -> System.out.println(str));
7.高级用法
字数: 0 字 时长: 0 分钟
7.1 基本数据类型优化
我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。
例如: mapTolnt、mapToLong、mapToDouble、flatMapTolnt、flatMapToDouble等。
7.2 并行流
当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解和认识。而如果我们使用Stream的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。
rallel方法可以把串行流转换成并行流。
也可以通过parallelStream直接获取并行流对象。
//优化前:串行的方式
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer i = stream
.filter(num -> num > 5)
.reduce((result, element) -> result + element)
.get();
System.out.println(i);
//优化后:调用parallel()方法即可实现并行流
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer i2 = stream2.parallel()
.peek(integer -> System.out.println(integer + Thread.currentThread().getName()))
.filter(num -> num > 5)
.reduce((result, element) -> result + element)
.get();
System.out.println(i2);
//也可以通过parallelStream直接获取并行流对象。
authors.parallelStream()
.map(author -> author.getAge())
.mapToInt(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age +2)
.forEach(System.out::println);
7.3 peek()可以作为开发者测试使用
7.4 串行流与并行流的举例
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer i = stream
.peek(integer -> System.out.println(integer + Thread.currentThread().getName()))
.filter(num -> num > 5)
.reduce((result, element) -> result + element)
.get();
System.out.println(i);
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer i2 = stream2.parallel()
.peek(integer -> System.out.println(integer + Thread.currentThread().getName()))
.filter(num -> num > 5)
.reduce((result, element) -> result + element)
.get();
System.out.println(i2);
}