4.1
获取对象
(
应用
)
4.1.1 Optional
概述
可能包含或不包含非
null
值的容器对象
4.1.2方法介绍
方法名
|
说明
|
---|---|
static Optional of(T value)
|
获取一个
Optional
对象,封装的是非
null
值的对象
|
static Optional ofNullable(T value)
| 获取一个optional对象,optional封装的值对象可以是 null也可以不是null |
4.1.3示例代码
public class
OptionalDemo1
{
public static
void
main
(
String
[]
args
) {
//method1();
//public static <T> Optional<T> ofNullable(T value)
//
获取一个
Optional
对象,
Optional
封装的值对象可以是
null
也可以不是
null
//Student s = new Student("zhangsan",23);
Student s
=
null
;
//ofNullable
方法,封装的对象可以是
null
,也可以不是
null
。
Optional
<
Student
>
optional
=
Optional
.
ofNullable
(
s
);
System
.
out
.
println
(
optional
);
}
private static
void
method1
() {
//static <T> Optional<T> of(T value)
获取一个
Optional
对象,封装的是非
null
值的对象
//Student s = new Student("zhangsan",23);
Student s
=
null
;
//Optional
可以看做是一个容器,里面装了一个引用数据类型的对象。
//
返回值就是
Optional
的对象
//
如果使用
of
方法,封装的对象如果为空,那么还是会抛出空指针异常
Optional
<
Student
>
optional1
=
Optional
.
of
(
s
);
System
.
out
.
println
(
optional1
);
}
}
4.2
常用方法
(
应用
)
4.2.1方法介绍
方法名
|
说明
|
T get()
|
如果存在值
,
返回值
,
否则抛出
NoSuchElementException
|
boolean isPresent()
|
如果存在值
,
则返回
true,
否则为
false
|
4.2.2
4.3处理空指针的方法(应用)
4.3.1方法介绍
方法名
|
说明
|
T orElse(T other)
|
如果不为空
,
则返回具体的值
,
否则返回参数中的值
|
TorElseGet(Supplier<extendsT>supplier)
| 如果不为空,则返回具体的值,否则返回由括号中 函数产生的结果 |
voidifPresent(Consumer<superT>action)
|
如果不为空
,
则使用该值执行给定的操作
,
否则不 执行任何操作
|
void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
|
如果不为空
,
则使用该值执行给定的操作
,
否则执 行给定的基于空的操作
|
4.3.2代码
public class
OptionalDemo3
{
public static
void
main
(
String
[]
args
) {
//method1();
//method2();
//method3();
//method4();
}
private static
void
method4
() {
//Student s = new Student("zhangsan",23);
Student s
=
null
;
Optional
<
Student
>
optional
=
Optional
.
ofNullable
(
s
);
//public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
、
//
如果不为空,则使用该值执行给定的操作,否则执行给定的基于空的操作。
optional
.
ifPresentOrElse
(
student
‐>
System
.
out
.
println
(
student
), ()
‐>
System
.
out
.
println
(
"
为空 了
"
));
}
private static
void
method3
() {
//Student s = new Student("zhangsan",23);
Student s
=
null
;
Optional
<
Student
>
optional
=
Optional
.
ofNullable
(
s
);
//ifPresent (Consumer<? super T> action)
//
如果不为空,则使用该值执行给定的操作,否则不执行任何操作
optional
.
ifPresent
(
student
‐>
System
.
out
.
println
(
student
));
}
private static
void
method2
() {
Student s
=
new
Student
(
"zhangsan"
,
23
);
//Student s = null;
Optional
<
Student
>
optional
=
Optional
.
ofNullable
(
s
);
//orElseGet(Supplier<? extends T> supplier)
//
如果不为空,则返回具体的值,否则返回由括号中函数产生的结果
Student student
=
optional
.
orElseGet
(()
‐>
new
Student
(
"lisi"
,
24
));
System
.
out
.
println
(
student
);
}
private static
void
method1
() {
//Student s = new Student("zhangsan",23);
Student s
=
null
;
Optional
<
Student
>
optional
=
Optional
.
ofNullable
(
s
);
//orElse(T other)
如果不为空,则返回具体的值,否则返回参数中的值
Student student
=
optional
.
orElse
(
new
Student
(
"lisi"
,
24
));
System
.
out
.
println
(
student
);
}
}