...
1.基本API的使用
of
Optional<String> s = Optional.of("2222");
String s1 = s.get();
System.out.println(s1);
2222
ifNullable
ifNullable |
为指定的值创建一个Optional,如果指定的值为null,则返回一个空的Optional |
public class TestBean {
public static void main(String[] args) {
User user = null;
Optional<User> s = Optional.ofNullable(user);
User user1 = s.get();
}
}
异常 空指针
isPrensent
isPrensent |
如果值存在返回true,不存在返回false |
public class TestBean {
public static void main(String[] args) {
User user = null;
Optional<User> s = Optional.ofNullable(user);
boolean present = s.isPresent();
System.out.println(present);
}
}
false
get
get |
如果有值则返回,没有值抛出NoSuchElementException异常 |
public class TestBean {
public static void main(String[] args) {
User user = null;
Optional<User> s = Optional.ofNullable(user);
User user1 = s.get();
}
}
异常 空指针
ifPresent
ifPresent |
如果有值,则为其调用consumer接口,否则不做处理 |
public class TestBean {
public static void main(String[] args) {
User user = new User();
Optional<User> s = Optional.ofNullable(user);
s.ifPresent((value)-> System.out.println(value));
}
}
orElse
public class TestBean {
public static void main(String[] args) {
User user =null;
Optional<User> s = Optional.ofNullable(user);
User user1 = s.orElse(new User());
}
}
orElseGet
orElseGet |
他和orElse的区别在于,orElse将传入的值作为默认值,而他可以接受supplier接口实现默认值 |
public class TestBean {
public static void main(String[] args) {
User user =null;
Optional<User> s = Optional.ofNullable(user);
User user1 = s.orElseGet(()->{
User user2 = new User();
user2.setName("wwww");
return user2;
});
}
}
orElseThrow
orElseThrow |
有值返回,没有值抛出supplier接口创建的异常 |
public class TestBean {
public static void main(String[] args) {
User user =null;
Optional<User> s = Optional.ofNullable(user);
try {
User user1 = s.orElseThrow(()->{
return new Exception();
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
map
map |
有值,对其执行调用mapping函数得到返回值,如果返回值不为null,则创建包含mapping返回值的optional作为map的返回值,否则返回空的optional |
public class TestBean {
public static void main(String[] args) {
User user = new User();
user.setName("wwww");
Optional<User> s = Optional.ofNullable(user);
Optional<String> s1 = s.map((up) -> up.getName().toUpperCase());
String s2 = s1.get();
System.out.println(s2);
}
}
WWW
flatMap
flatMap |
他map类似,区别在于他调用结束的时候,不会对optional做一个封装 |
User user = new User();
user.setName("wwww");
Optional<User> s = Optional.ofNullable(user);
Optional<String> s1 = s.flatMap((up) -> Optional.of(up.getName().toUpperCase()));
filter
filter |
有值,返回满足条件的optional,否则返回空的optional |
public class TestBean {
public static void main(String[] args) {
User user = new User();
user.setName("wwww");
Optional<User> s = Optional.ofNullable(user);
Optional<User> www = s.filter(up -> up.getName().equals("www"));
}
}