前言
写这篇文章的原因是因为Java8现在依然是Java开发使用的主流,现在开始推Java11,然后再过一段时间应该会推Java14,所以我就想写一下Java8的特性,本文是通过学习所得,内容是视频文本5%+自我的理解95%。
视频链接
https://www.bilibili.com/video/BV1kK4y1p7M2
知识点解读
函数编程
关注于流程而非具体实现。可以将函数作为参数或返回值。所有数据的操作都通过函数来实现。可以理解为数学中的函数。较新的语言基本上追求语法上的简洁基本都有支持。即我们所说的回调!
匿名内部类
如果接口的实现类(或者是父类的子类),只需要使用唯一的一次那么这种情况下就可以省略掉该类的定义,而改为使用匿名内部类
匿名内部类的定义格式:
接口名称 对象名 = new 接口名称(){
//覆盖重写所有抽象方法
};
注意点:
- 匿名内部类,在创建对象的时候,只能创建唯一一个如果希望多次创建对象,而且类的内容一样化,就必须使用单独定义的实现类了。(或者多次创建)
- 匿名对象,在【调用方法的时候】只能调用唯一一次。如果希望同一个对象调用多个方法,那么对象必须取个名字(或者多次调用)
- 匿名内部类是省略了【实现类/子类名称】,匿名对象省略了【对象名称】
关于set去重
set底层是object,object中equals是this.obj==obj 这里看的是内存地址,而我们通常使用HashSet进行实现,hashset是hashmap进行实现的,hash是散列的,所以无序,源码中有一行private static final Object PRESENT = new Object();
和private transient HashMap<E,Object> map;
可以看出传入的值作为key值,PERSENT作为value来存储到map中,如果key值相同,将会覆盖。所以可以去重。
接口
在jdk8之前,interface之中可以定义变量和方法,变量必须是public、static、final 的,方法必须是public、abstract的,由于这些修饰符都是默认的。
在JDK 1.8开始支持使用static和l default 修饰可以写方法体,不需要子类重写。方法:
普通方法可以有方法体
抽象方法没有方法体需要子类实现重写。
1.接口中无需使用public和abstract来进行指定变量和方法
我们在学习Java的时候相信都学过interface是抽象的,需要使用public和abstract来对接口中的变量(变量无需abstract)和方法进行指定,但是自Java8开始,推荐我们不去写public和abstract,因为这些都是interface默认就带有的
原始
修改
2.一成不变的default关键字
在Java中学习接口的时候相信大家都听老师说过,在接口中都是抽象方法,是不可以定义方法体的,方法只有头,我们需要在类中对接口的方法进行实现,但是自Java8开始提供了default关键字
作用
使得我们在接口中也可以去书写方法体,在进行函数编程(请看知识点解读)的时候默认方法就可以进行扩展
实现类中无需进行重写
原始
修改
使用
在使用上我估计大家也能够猜到
其实和寻常的函数使用是一样的,唯一不同的是使用default之后无需在实现类中进行重写,当然你想重写也是可以的,但是如果你要进行重写为什么还去定义default呢?
即一成不变所以才要定义为default
public static void main(String[] args) {
InterDemo2Impl interDemo2 = new InterDemo2Impl();
interDemo2.test2();
}
3.static关键字
static关键字用于声明静态方法或静态变量
使用他也可以在接口中进行方法体的书写
在调用时也和平时一样
void staticTest(){
System.out.println("test");
}
-------------------------
InterDemo2.staticTest();
lambda表达式
Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。Lambda表达式可以表示闭包(注意和数学传统意义上的不同)。
Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁。当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口。下面这个例子就是使用Lambda语法来代替匿名的内部类,代码不仅简洁,而且还可读。
—— from baidu
优点
有效简化代码(特别是匿名内部类【请看知识点解读】)
依赖
使用Lambda表达式依赖于函数接口
- 在接口中只能够允许有一个抽象方法
- 在函数接口中定义object类中方法
- 使用默认或者静态方法
- @ FunctionalInterface标识该接口为函数接口
实例
定义一个函数接口
package cn.learn.aboutLambda;
@FunctionalInterface
public interface MyFuncInterface {
void test();
}
联系上面的default和static,你就会发现之前说的有助于拓展函数编程的意思了
Object类中的方法可以在函数接口中进行重写
使用匿名内部类new出接口
实现方式1
package cn.learn;
import cn.learn.aboutLambda.LambdaDemo1;
public class LambdaTest {
public static void main(String[] args) {
//匿名内部类new接口实现方法
LambdaDemo1 lambdaDemo1 = new LambdaDemo1() {
@Override
public void test1() {
System.out.println("test");
}
};
lambdaDemo1.test1();
}
}
实现方式2
package cn.learn;
import cn.learn.aboutLambda.LambdaDemo1;
public class LambdaTest {
public static void main(String[] args) {
//匿名内部类new接口实现方法
new LambdaDemo1() {
@Override
public void test1() {
System.out.println("test");
}
}.test1();
}
}
使用lambda修改
从上面两个实现来看代码冗余度很高
而使用lambda进行改写后
//lambda简化
((LambdaDemo1) () -> System.out.println("test")).test1();
基础语法
(参数)->{
代码块
}
无参实例
LambdaDemo2接口
package cn.learn.aboutLambda;
@FunctionalInterface
public interface LambdaDemo2 {
void noArgsLambda();
}
测试类
package cn.learn;
import cn.learn.aboutLambda.LambdaDemo2;
public class LambdaTest2 {
public static void main(String[] args) {
LambdaDemo2 lambdaDemo2 = ()->{
System.out.println("no args");
};
lambdaDemo2.noArgsLambda();
}
}
有参实例
package cn.learn.aboutLambda;
@FunctionalInterface
public interface LambdaDemo3 {
String argsLambda(String arg1,int arg2);
}
测试类
package cn.learn;
import cn.learn.aboutLambda.LambdaDemo3;
public class LambdaTest3 {
public static void main(String[] args) {
LambdaDemo3 lambdaDemo3 = (username, password) -> {
return username + password;
};
System.out.println(lambdaDemo3.argsLambda("zhansan",123456));
}
}
优化语法
//原始
返回值类型(接口) 变量名 = (参数)-> { 代码块 }
变量名 . 方法名()
如果方法体中仅有一条语句:
//优化
((返回值类型(接口)() -> 代码块). 方法名()
实例(无返回值无参单行)
原始:
LambdaDemo2 lambdaDemo2 = ()->{
System.out.println("no args");
};
lambdaDemo2.noArgsLambda();
优化:
((LambdaDemo2)()-> System.out.println("easy no args")).noArgsLambda();
实例(有返回值有参单行)
如果有返回值但是依旧是单行的话可以省略return
原始:
LambdaDemo3 lambdaDemo3 = (username, password) -> {
return username + password;
};
System.out.println(lambdaDemo3.argsLambda("zhansan",123456));
优化:
System.out.println(((LambdaDemo3)(username,password)->username+password).argsLambda("zhangsan",123456));
如果是单个参数的可以省略()
参数 -> 代码块
如果是多行{}和return不能省略,常规写
lambda集合遍历
原始
package cn.learn.aboutLambda;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class LambdaListTest {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("zhangsan");
arrayList.add("lisi");
arrayList.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
}
}
优化
package cn.learn.aboutLambda;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class LambdaListTest {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("zhangsan");
arrayList.add("lisi");
arrayList.forEach(System.out::println);
}
}
对比
Stream流
以非常方便精简的形式对集合进行遍历,过滤,排序等操作
使用Stream流将list集合转化为set
listnode
package cn.learn.steam.entity;
public class ListNode {
private int age;
private String name;
public ListNode() {
}
public ListNode(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ListNode{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
测试类
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListToSetSteam {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10,"zhangsan"));
list.add(new ListNode(12,"lisi"));
list.add(new ListNode(13,"wangwu"));
Stream<ListNode> stream = list.stream();
Set<ListNode> set = stream.collect(Collectors.toSet());
set.forEach(System.out::println);
}
}
注意点
上方代码大家应该也能看的出,在ListNode类中没有重写equals方法
所以当从list转化为set时不会进行去重操作(仅限复杂数据结构(自定类等)),所以如果你add两个相同的对象由于内存地址不同所以set不会认为他们是同一个对象
使用Stream流将list转化为set实现去重
只要去重写equals和hashcode方法即可
package cn.learn.steam.entity;
import java.util.Objects;
public class ListNode {
private int age;
private String name;
public ListNode() {
}
public ListNode(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ListNode{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListNode listNode = (ListNode) o;
return age == listNode.age && name.equals(listNode.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
}
测试类
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListToSetSteam {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10,"zhangsan"));
list.add(new ListNode(12,"lisi"));
list.add(new ListNode(13,"wangwu"));
list.add(new ListNode(13,"wangwu"));
Stream<ListNode> stream = list.stream();
Set<ListNode> set = stream.collect(Collectors.toSet());
set.forEach(System.out::println);
}
}
Stream流list转map
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListToMapStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
Stream<ListNode> stream = list.stream();
//参数
//1.list集合类型
//2.String:key的类型
Map<String, ListNode> collect = stream.collect(Collectors.toMap(new Function<ListNode, String>() {
@Override
public String apply(ListNode listNode) {
return listNode.getName();
}
}, new Function<ListNode, ListNode>() {
@Override
public ListNode apply(ListNode listNode) {
return listNode;
}
}
));
collect.forEach(new BiConsumer<String, ListNode>() {
@Override
public void accept(String s, ListNode listNode) {
System.out.println(s + "---" + listNode);
}
});
}
}
lambda表达式优化
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListToMapStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
Stream<ListNode> stream = list.stream();
//参数
//1.list集合类型
//2.String:key的类型
Map<String, ListNode> collect = stream.collect(Collectors.toMap(listNode -> listNode.getName(), listNode -> listNode
));
collect.forEach((s, listNode) -> System.out.println(s + "---" + listNode));
}
}
优化点
Map<String, ListNode> collect = stream.collect(Collectors.toMap(listNode -> listNode.getName(), listNode -> listNode
));
collect.forEach((s, listNode) -> System.out.println(s + "---" + listNode));
可以看到lambda进行优化后不仅代码量减少很多,而且参数上直接对应
使用Stream进行求和,求最大值,求最小值
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Stream;
public class GetSumSrtream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
Stream<ListNode> stream = list.stream();
//求和
// Optional<ListNode> sum = stream.reduce((listNode, listNode2) -> {
// ListNode listNode1 = new ListNode(listNode.getAge() + listNode2.getAge(), "sum");
// return listNode1;
// });
//获取最大值
// System.out.println(sum.get());
// Optional<ListNode> max = stream.max((o1, o2) -> o1.getAge() - o2.getAge());
// System.out.println(max.get());
//获取最小值
Optional<ListNode> min = stream.min((o1, o2) -> o1.getAge() - o2.getAge());
System.out.println(min.get());
}
}
Stream流使用match进行条件匹配
- anyMatch表示,判断的条件里,任意一个元素成功,返回true
- allMatch表示,判断条件里的元素,所有的都是,返回true
- noneMatch跟 allMatch相反,判断条件里的元素,所有的都不是,返回true
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class MatchStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
Stream<ListNode> stream = list.stream();
boolean a = stream.allMatch(listNode -> "lisi".equals(listNode.getName()));
boolean b = stream.anyMatch(listNode -> "lisi".equals(listNode.getName()));
boolean c = stream.noneMatch(listNode -> "lisi".equals(listNode.getName()));
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Stream过滤器
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class FilterStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
Stream<ListNode> stream = list.stream();
Stream<ListNode> listNodeStream = stream.filter(listNode -> "lisi".equals(listNode.getName()) || listNode.getAge() > 12);
listNodeStream.forEach(System.out::println);
}
}
使用Stream流中的limit取数据
取出的数据是按照顺序排列的
取前n条数据
stream.limit(4).forEach(System.out::println);
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.stream.Stream;
public class LimitStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
list.add(new ListNode(22, "蓝山"));
list.add(new ListNode(133, "牛栏山"));
Stream<ListNode> stream = list.stream();
stream.limit(4).forEach(System.out::println);
}
}
忽略前n条数据取第n+1 …的数据
stream.skip(4).forEach(System.out::println);
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.stream.Stream;
public class LimitStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
list.add(new ListNode(22, "蓝山"));
list.add(new ListNode(133, "牛栏山"));
Stream<ListNode> stream = list.stream();
stream.skip(4).forEach(System.out::println);
}
}
忽略前n条数据取第n+1 …到m条数据
stream.skip(1).limit(5).forEach(System.out::println);
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.stream.Stream;
public class LimitStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(12, "lisi"));
list.add(new ListNode(13, "wangwu"));
list.add(new ListNode(22, "蓝山"));
list.add(new ListNode(133, "牛栏山"));
Stream<ListNode> stream = list.stream();
stream.skip(1).limit(5).forEach(System.out::println);
}
}
使用Stream流进行排序
stream.sorted((listNode1, listNode2) -> listNode1.getAge() - listNode2.getAge()).forEach(System.out::println);
package cn.learn.steam;
import cn.learn.steam.entity.ListNode;
import java.util.ArrayList;
import java.util.stream.Stream;
public class SortStream {
public static void main(String[] args) {
ArrayList<ListNode> list = new ArrayList<>();
list.add(new ListNode(133, "牛栏山"));
list.add(new ListNode(10, "zhangsan"));
list.add(new ListNode(13, "wangwu"));
list.add(new ListNode(22, "蓝山"));
list.add(new ListNode(12, "lisi"));
Stream<ListNode> stream = list.stream();
stream.sorted((listNode1, listNode2) -> listNode1.getAge() - listNode2.getAge()).forEach(System.out::println);
}
}
JDK8内置函数接口
idea查看位置
并行流
不使用并行流
package cn.learn.other;
public class TestDemo1 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
long sum = 0L;
for (long i = 1L; i < 50000000000L; i++) {
sum += i;
}
System.out.println(sum);
long end = System.currentTimeMillis();
//time:12973 ms
System.out.println("time:" + (end - start));
}
}
花费时间大约13s
使用并行流
package cn.learn.other;
import java.util.OptionalLong;
import java.util.function.LongBinaryOperator;
import java.util.stream.LongStream;
public class TestDemo1Change {
public static void main(String[] args) {
long start = System.currentTimeMillis();
LongStream longStream = LongStream.rangeClosed(1L, 50000000000L);
OptionalLong reduce = longStream.parallel().reduce((n1, n2) -> n1 + n2);
System.out.println(reduce.getAsLong());
long end = System.currentTimeMillis();
//time:11683 ms
System.out.println("time:" + (end - start));
}
}
花费时间11.5s
使用多线程处理大的任务拆分成n多小的任务在计算在将结果合并fork join
但是在这里你会发现好像并没快多少,甚至是基本上差不多
按照理论应该是会变快更多
你别说当时我也迷了,然后在网上找了张图
然后又想了一下,我的电脑硬件配置来说还可以所以看不出多少性能上的提示
况且当时我还开着服务器和虚拟机,cpu的占有率自然低了
方法引入
需要结合 lambda表达式能够让代码变得更加精简。
- 静态方法引入:类名:(静态)方法名称
- 对象方法引入类名::实例方法名称
- 实例方法引入new对象对象实例方法引入
- 构造函数引入类名:new
规范
方法参数列表、返回类型与函数接口参数列表与返回类型必须要保持一致。
实例
1.静态方法
接口
package cn.learn.other.inter;
public interface StaticInter {
String get(String str1,String str2);
}
测试类
package cn.learn.other;
import cn.learn.other.inter.StaticInter;
public class TestStaticInter {
public static void main(String[] args) {
StaticInter staticInter = TestStaticInter::statciGet;
System.out.println(staticInter.get("java ", "staticFunc"));
}
public static String statciGet(String str1, String str2) {
return str1 + str2;
}
}
对应图示
2.实例方法
package cn.learn.other;
import cn.learn.other.inter.StaticInter;
import java.util.Comparator;
public class TestRealInter {
public static void main(String[] args) {
TestRealInter testRealInter = new TestRealInter();
StaticInter staticInter = testRealInter::realGet;
System.out.println(staticInter.get("java ", "realFunc"));
}
public String realGet(String str1, String str2) {
return str1 + str2;
}
}
3.构造函数
实体类
package cn.learn.other.entity;
public class TestEntity {
private String username;
private String password;
public TestEntity(String username, String password) {
this.username = username;
this.password = password;
}
public TestEntity() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "TestEntity{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
接口
package cn.learn.other.inter;
import cn.learn.other.entity.TestEntity;
@FunctionalInterface
public interface EntityInter {
TestEntity testFun();
}
测试类
package cn.learn.other;
import cn.learn.other.entity.TestEntity;
import cn.learn.other.inter.EntityInter;
public class TestBuildInter {
public static void main(String[] args) {
EntityInter entityInter = TestEntity::new;
System.out.println(entityInter.testFun());
}
}
关于为什么会出现结果为
其实只要调试一下就可以看出来了
首先进入
然后
这个就是原理,就两步,构造无参对对象进行null比较,true直接调用toString方法
所以toString需要我们进行重写
4.对象方法
接口
package cn.learn.other.inter;
import cn.learn.other.TestObjInter;
@FunctionalInterface
public interface ObjInter {
String get(TestObjInter testObjInter);
}
测试类
package cn.learn.other;
import cn.learn.other.inter.ObjInter;
public class TestObjInter {
public static void main(String[] args) {
// ObjInter objInter1 = new ObjInter() {
// @Override
// public String get(TestObjInter testObjInter) {
// return testObjInter.objGet();
// }
// };
//改写
ObjInter objInter = TestObjInter::objGet;
System.out.println(objInter.get(new TestObjInter()));
}
public String objGet(){
return "obj func";
}
}
Optional
Optional类是一个可以为null 的容器对象。如果值存在则isPresent()方法会返回true,调用get(方法会返回该对象。
Optional是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
Optional类的引入很好的解决空指针异常。
源码
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.util;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* A container object which may or may not contain a non-null value.
* If a value is present, {@code isPresent()} will return {@code true} and
* {@code get()} will return the value.
*
* <p>Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link #orElse(java.lang.Object) orElse()}
* (return a default value if value not present) and
* {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
* of code if the value is present).
*
* <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Optional} may have unpredictable results and should be avoided.
*
* @since 1.8
*/
public final class Optional<T> {
/**
* Common instance for {@code empty()}.
*/
private static final Optional<?> EMPTY = new Optional<>();
/**
* If non-null, the value; if null, indicates no value is present
*/
private final T value;
/**
* Constructs an empty instance.
*
* @implNote Generally only one empty instance, {@link Optional#EMPTY},
* should exist per VM.
*/
private Optional() {
this.value = null;
}
/**
* Returns an empty {@code Optional} instance. No value is present for this
* Optional.
*
* @apiNote Though it may be tempting to do so, avoid testing if an object
* is empty by comparing with {@code ==} against instances returned by
* {@code Option.empty()}. There is no guarantee that it is a singleton.
* Instead, use {@link #isPresent()}.
*
* @param <T> Type of the non-existent value
* @return an empty {@code Optional}
*/
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
/**
* Constructs an instance with the value present.
*
* @param value the non-null value to be present
* @throws NullPointerException if value is null
*/
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
/**
* Returns an {@code Optional} with the specified present non-null value.
*
* @param <T> the class of the value
* @param value the value to be present, which must be non-null
* @return an {@code Optional} with the value present
* @throws NullPointerException if value is null
*/
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
/**
* If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if there is no value present
*
* @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
/**
* If a value is present, and the value matches the given predicate,
* return an {@code Optional} describing the value, otherwise return an
* empty {@code Optional}.
*
* @param predicate a predicate to apply to the value, if present
* @return an {@code Optional} describing the value of this {@code Optional}
* if a value is present and the value matches the given predicate,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the predicate is null
*/
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
/**
* If a value is present, apply the provided mapping function to it,
* and if the result is non-null, return an {@code Optional} describing the
* result. Otherwise return an empty {@code Optional}.
*
* @apiNote This method supports post-processing on optional values, without
* the need to explicitly check for a return status. For example, the
* following code traverses a stream of file names, selects one that has
* not yet been processed, and then opens that file, returning an
* {@code Optional<FileInputStream>}:
*
* <pre>{@code
* Optional<FileInputStream> fis =
* names.stream().filter(name -> !isProcessedYet(name))
* .findFirst()
* .map(name -> new FileInputStream(name));
* }</pre>
*
* Here, {@code findFirst} returns an {@code Optional<String>}, and then
* {@code map} returns an {@code Optional<FileInputStream>} for the desired
* file if one exists.
*
* @param <U> The type of the result of the mapping function
* @param mapper a mapping function to apply to the value, if present
* @return an {@code Optional} describing the result of applying a mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null
*/
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
/**
* If a value is present, apply the provided {@code Optional}-bearing
* mapping function to it, return that result, otherwise return an empty
* {@code Optional}. This method is similar to {@link #map(Function)},
* but the provided mapper is one whose result is already an {@code Optional},
* and if invoked, {@code flatMap} does not wrap it with an additional
* {@code Optional}.
*
* @param <U> The type parameter to the {@code Optional} returned by
* @param mapper a mapping function to apply to the value, if present
* the mapping function
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null or returns
* a null result
*/
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
/**
* Return the contained value, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present value
* @throws X if there is no value present
* @throws NullPointerException if no value is present and
* {@code exceptionSupplier} is null
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
/**
* Indicates whether some other object is "equal to" this Optional. The
* other object is considered equal if:
* <ul>
* <li>it is also an {@code Optional} and;
* <li>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code equals()}.
* </ul>
*
* @param obj an object to be tested for equality
* @return {code true} if the other object is "equal to" this object
* otherwise {@code false}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Optional)) {
return false;
}
Optional<?> other = (Optional<?>) obj;
return Objects.equals(value, other.value);
}
/**
* Returns the hash code value of the present value, if any, or 0 (zero) if
* no value is present.
*
* @return hash code value of the present value or 0 if no value is present
*/
@Override
public int hashCode() {
return Objects.hashCode(value);
}
/**
* Returns a non-empty string representation of this Optional suitable for
* debugging. The exact presentation format is unspecified and may vary
* between implementations and versions.
*
* @implSpec If a value is present the result must include its string
* representation in the result. Empty and present Optionals must be
* unambiguously differentiable.
*
* @return the string representation of this instance
*/
@Override
public String toString() {
return value != null
? String.format("Optional[%s]", value)
: "Optional.empty";
}
}
主要方法
1.ofNullable
判断当前传入,如果当前传入的泛型的值为空则返回一个空的可选值。若非空返回当前传入泛型的指定值
2.of
与ofNullable基本相同,不同的是无法传递空值会报错
3.isPresent
判断当前传入值,若为空则返回false,不为空则为true
4.filter
判断传入值,若传入值为空则返回空的可选值,使用get方法获取则会抛出NullPointerException的异常,若传入值不为空则返回一个描述该入参的可选值描述,多和isPresent方法连用
5.orElse
该方法用于当入参为空值时设立默认值
Optional.ofNullable(null).orElse("default")
6.orElseGet
以函数接口的方式设立默认值
Optional.ofNullable(nullValue).orElse(()->{
nullValue = "default";
return nullValue;
})
可以继续优化使用方法引入的方式
7.ifPresent
在传入值不为空的情况下调用,否则不执行
optional.ifPresent(System.out::println)
8.map
如果传入值存在不为空则返回映射函数,为空则返回空的可选值
Optional< FileInputStream > fis = names.stream().filter(name -> !isProcessedYet(name)) .findFirst() .map(name -> new FileInputStream(name));
在这里,findFirst返回一个可选的< String>,然后map返回所需文件(如果存在)的可选的< FileInputStream>。
//优化前
OrderEnity order = new OrderEnity(123456, "zhangsan");
if (order != null) {
String orderName = order.getOrderName();
if (orderName != null) {
return orderName.toUpperCase();
}
}
//优化
return Optional.ofNullable(order).map(orderEnity -> orderEnity.getOrderName()).map(orderName -> orderName.toUpperCase()).orElse(null);
package cn.learn.optional;
import java.util.Optional;
public class OptTestDemo3 {
public static void main(String[] args) {
String orderName = OptTestDemo3.getOrderName();
System.out.println(orderName);
}
public static String getOrderName() {
//优化前
OrderEnity order = new OrderEnity(123456, "zhangsan");
// if (order != null) {
// String orderName = order.getOrderName();
// if (orderName != null) {
// return orderName.toUpperCase();
// }
// }
//优化
return Optional.ofNullable(order).map(orderEnity -> orderEnity.getOrderName()).map(orderName -> orderName.toUpperCase()).orElse(null);
}
}
判断对象是否为空
package cn.learn.optional;
import java.util.Optional;
/**
* 判断对象是否为空
*/
public class OptTestDemo1 {
public static void main(String[] args) {
/*String user = null;
Optional<String> optional = Optional.ofNullable(user);
//Exception in thread "main" java.util.NoSuchElementException: No value present
System.out.println(optional.get());*/
String user = "zhangsan";
Optional<String> optional = Optional.ofNullable(user);
System.out.println(optional.get());
}
}
解释为什么空值打印的是异常
点开源码,你会发现get()方法若值为空打印的是NoSuchElementException(“No value present”);
这个异常处理
而我们不使用get()取值打印的是:
Optional参数过滤
package cn.learn.optional;
import java.util.Optional;
public class OptTestDemo2 {
public static void main(String[] args) {
String username = null;
Optional<String> optional = Optional.ofNullable(username).filter(s -> username.equals(s));
System.out.println(optional);
}
}
使用Optional避免空指针问题
看到isPresent方法相信大家已经知道怎么避免该问题了
方法1(isPresent+if判断)
当我们使用ofNullable进行值接收之后我们要进行isPresent的判断,为true则进行get获取否则进行自定义处理即可
方法2(ifPresent)
方法1的优化