类作用
Optional作为处理空指针的类,主要用途是作为一种返回类型,在获得该类型的一个实例后,如果存在值,可以提取该值;如果不存在值,可以设置一个默认值。
常用写法
public class OptionalTest {
/**
* 测试Optional of()、ofNullable()
*/
private static void test1(){
// User user = null;
User user = new User("tom",23);
//of()当对象为空时会抛出异常,可以使用ofNullable()
Optional<User> userOptional = Optional.ofNullable(user);
//判断当前对象是否不为空
System.out.println(userOptional.isPresent());
//获取对象的值
System.out.println(userOptional.get().getName());
}
/**
* orElseThrow():对象为空时设置抛出异常
*/
private static void test2(){
// User user = null;
User user = new User("tom",23);
User userOptional = Optional.ofNullable(user)
.orElseThrow( () -> new IllegalArgumentException());
}
/**
* orElseGet():对象为空时设置默认值
*/
private static void test3(){
User user = null;
// User user = new User("tom",23);
User userOptional = Optional.ofNullable(user)
.orElseGet(() -> new User("default",23));
System.out.println(userOptional);
}
/**
* 对值进行转换
* Map()返回Optional中经过封装的结果,
* 使我们可以在后续附加一些操作,比如orElse()
*/
private static void test4(){
User user = null;
// User user = new User("tom",23);
String name = Optional.ofNullable(user)
.map(u -> u.getName()).orElse("jack");
System.out.println(name);
}
/**
* 过滤操作
* 保留大于20岁的用户
*/
private static void test5(){
// User user = new User("tom",23);
// User result = Optional.ofNullable(user)
// .filter(u -> u.getAge() > 20)
// .orElseGet(() -> new User("default",30));
// System.out.println(result.getName());
//处理list
User user = new User("tom",33);
User user1 = new User("marry",13);
List<User> userList = new ArrayList<>();
userList.add(user);
userList.add(user1);
List<User> userAgeLess20 = userList.stream()
.filter(u -> u.getAge() < 20)
.collect(Collectors.toList());
System.out.println(userAgeLess20);
}
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
}
}
User Bean类
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
参考:https://www.jianshu.com/p/63830b7cb743