一、API介绍
of()
功能:创建Optional实例 注意:创建对象时传入的参数不能为null。如果传入参数为null,则抛出NullPointerException 。
public static void of() {
Optional<String> notNullOptional = Optional.of("xiaoxian");
try {
Optional<String> nullOptional = Optional.of(null);
} catch (NullPointerException e) {
System.out.println("【of()】" + e.getMessage());
e.printStackTrace();
}
}
ofNullable()
功能:创建Optional实例 注意:如果指定的值为null,则返回一个空的Optional。
public static void ofNullable() {
Optional<String> notNullOptional = Optional.ofNullable("xiaoxian");
Optional<String> nullOptional = Optional.ofNullable(null);
}
empty()
功能:创建空的Optional实例
public static void empty() {
Optional<String> emptyOptional = Optional.empty();
}
get()
功能:获取Optional实例值 注意:如果实例值非null,就返回实例值,否则抛出NoSuchElementException
public static void get() {
System.out.println("【get()】" + notNullOptional.get());
try {
System.out.println("【get()】" + nullOptional.get());
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
isPresent()
功能:检查Optional实例是否包含值。如果值存在返回true,否则返回false
public static void isPresent() {
System.out.println("【isPresent()】" + notNullOptional.isPresent());
System.out.println("【isPresent()】" + nullOptional.isPresent());
}
ifPresent()
功能:检查Optional实例是否有值,如果实例值非null,就执行lambda表达式,否则不处理
public static void ifPresent() {
notNullOptional.ifPresent(s -> {
s = s + " love java";
System.out.println("【ifPresent()】" + s);
});
System.out.println("【ifPresent()】" + notNullOptional.get());
}
orElse()
功能:检查Optional实例是否有值,如果实例非null,就返回实例值,否则返回指定的其它值。
public static void orElse() {
System.out.println("【orElse()】" + notNullOptional.orElse("There is no value present!"));
System.out.println("【orElse()】" + nullOptional.orElse("xiaoxian 666"));
}
orElseGet()
功能:检查Optional实例是否有值,如果实例值非null,就返回实例值,否则返回lambda表达式的值。
public static void orElseGet() {
System.out.println("【orElseGet()】" + notNullOptional.orElseGet(() -> "Default Value"));
System.out.println("【orElseGet()】" + nullOptional.orElseGet(() -> "Default Value"));
}
orElseThrow()
功能:检查Optional实例是否有值,如果实例值非null,就不做任何处理,否则抛异常Exception。
public static void orElseThrow() {
try {
notNullOptional.orElseThrow(Exception::new);
} catch (Exception e) {
e.printStackTrace();
}
try {
nullOptional.orElseThrow(Exception::new);
} catch (Throwable e) {
System.out.println("【orElseThrow()】" + e.getMessage());
e.printStackTrace();
}
}
map()
功能:对Optional实例值进行修改 注意:如果Optional实例值非null,就执行map(lambda表达式,任意类型),返回新的Optional实例,否则返回空Optional。
public static void map() {
Optional<String> notNullToUpperCase = notNullOptional.map((value) -> value.toUpperCase());
System.out.println("【map()】" + notNullToUpperCase.orElse("No value found"));
Optional<Integer> notNullToInteger = notNullOptional.map((value) -> 1);
System.out.println("【map()】" + notNullToInteger.orElse(2));
Optional<String> emptyToUpperCase = nullOptional.map((value) -> value.toUpperCase());
System.out.println("【map()】" + emptyToUpperCase.orElse("No value found"));
}
flatMap()
功能:对Optional实例值进行修改 注意:flatMap()与 map()类似,区别在于:传入方法的lambda表达式的返回类型 map():lambda表达式返回值可以是任意类型,在map函数返回之前会包装为Optional flatMap:lambda表达式返回值必须是Optionl实例,不会把结果包装为Optional
public static void flatMap() {
Optional<String> notNullToUpperCase = notNullOptional.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println("【flatMap()】" + notNullToUpperCase.orElse("No value found"));
Optional<String> optional = nullOptional.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println("【flatMap()】" + optional.orElse("No value found"));
}
filter()
功能:判断Option实例有值,并且满足条件 注意:如果有值并且满足条件,就返回该Optional,否则返回空Optional。
public static void filter() {
Optional<String> filterTrue = notNullOptional.filter((value) -> value.length() > 6);
System.out.println("【filter】" + filterTrue.orElse("不滿足filter條件"));
Optional<String> filterFalse = notNullOptional.filter((value) -> value.length() > 10);
System.out.println("【filter】" + filterFalse.orElse("不滿足filter條件"));
}
二、推荐写法
1、如果实例值不为null,就返回值,否则为null
User user1 = userOptional.isPresent() ? userOptional.get() : null;
User user2 = userOptional.orElse(null);
2、如果实例值不为null,就返回值,否则进行指定操作
User user3 = userOptional.isPresent() ? userOptional.get(): getUser();
User user4 = userOptional.orElseGet(() -> getUser());
3、如果实例值不为null,就进行指定操作
if (userOptional.isPresent()) {
System.out.println(userOptional.get());
}
userOptional.ifPresent(System.out::println);
if (userOptional.isPresent()) {
getUser();
}
userOptional.ifPresent(e->getUser());
4、如果实例值不为null,就获取实例值,并进行指定操作
List<String> list = null;
if(userOptional.isPresent()) {
list = userOptional.get().getCourseList();
} else {
list = Collections.emptyList();
}
list = userOptional.map(u -> u.getCourseList()).orElse(Collections.emptyList());
getName(new User("xiaoxian"));
getNameNew(new User("xiaoxian"));
public static String getName(User user){
if(user != null) {
String name = user.getName();
if(name != null) {
return name.toUpperCase();
} else {
return null;
}
} else {
return null;
}
}
public static String getNameNew(User user){
Optional<User> userOptional = Optional.ofNullable(user);
return userOptional.map(u -> u.getName())
.map(name -> name.toUpperCase())
.orElse(null);
}
三、API示例代码
import java.util.NoSuchElementException;
import java.util.Optional;
public class TestOptional {
public static Optional<String> notNullOptional = Optional.of("xiaoxian");
public static Optional<String> nullOptional = Optional.ofNullable(null);
public static void main(String args[]) {
of();
ofNullable();
empty();
get();
isPresent();
ifPresent();
orElse();
orElseGet();
orElseThrow();
map();
flatMap();
filter();
}
public static void of() {
Optional<String> notNullOptional = Optional.of("xiaoxian");
try {
Optional<String> nullOptional = Optional.of(null);
} catch (NullPointerException e) {
System.out.println("【of()】" + e.getMessage());
e.printStackTrace();
}
}
public static void ofNullable() {
Optional<String> notNullOptional = Optional.ofNullable("xiaoxian");
Optional<String> nullOptional = Optional.ofNullable(null);
}
public static void empty() {
Optional<String> emptyOptional = Optional.empty();
}
public static void get() {
System.out.println("【get()】" + notNullOptional.get());
try {
System.out.println("【get()】" + nullOptional.get());
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
public static void isPresent() {
System.out.println("【isPresent()】" + notNullOptional.isPresent());
System.out.println("【isPresent()】" + nullOptional.isPresent());
}
public static void ifPresent() {
notNullOptional.ifPresent(s -> {
s = s + " love java";
System.out.println("【ifPresent()】" + s);
});
System.out.println("【ifPresent()】" + notNullOptional.get());
}
public static void orElse() {
System.out.println("【orElse()】" + notNullOptional.orElse("There is no value present!"));
System.out.println("【orElse()】" + nullOptional.orElse("xiaoxian 666"));
}
public static void orElseGet() {
System.out.println("【orElseGet()】" + notNullOptional.orElseGet(() -> "Default Value"));
System.out.println("【orElseGet()】" + nullOptional.orElseGet(() -> "Default Value"));
}
public static void orElseThrow() {
try {
notNullOptional.orElseThrow(Exception::new);
} catch (Exception e) {
e.printStackTrace();
}
try {
nullOptional.orElseThrow(Exception::new);
} catch (Throwable e) {
System.out.println("【orElseThrow()】" + e.getMessage());
e.printStackTrace();
}
}
public static void map() {
Optional<String> notNullToUpperCase = notNullOptional.map((value) -> value.toUpperCase());
System.out.println("【map()】" + notNullToUpperCase.orElse("No value found"));
Optional<Integer> notNullToInteger = notNullOptional.map((value) -> 1);
System.out.println("【map()】" + notNullToInteger.orElse(2));
Optional<String> emptyToUpperCase = nullOptional.map((value) -> value.toUpperCase());
System.out.println("【map()】" + emptyToUpperCase.orElse("No value found"));
}
public static void flatMap() {
Optional<String> notNullToUpperCase = notNullOptional.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println("【flatMap()】" + notNullToUpperCase.orElse("No value found"));
Optional<String> optional = nullOptional.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println("【flatMap()】" + optional.orElse("No value found"));
}
public static void filter() {
Optional<String> filterTrue = notNullOptional.filter((value) -> value.length() > 6);
System.out.println("【filter】" + filterTrue.orElse("不滿足filter條件"));
Optional<String> filterFalse = notNullOptional.filter((value) -> value.length() > 10);
System.out.println("【filter】" + filterFalse.orElse("不滿足filter條件"));
}
}
四、推荐示例代码
import java.util.Collections;
import java.util.List;
public class UseOptional {
public static User getUser() {
return new User("xiaoxian");
}
public static void main(String[] args) {
Optional<User> userOptional = Optional.of(new User("xiaoxian"));
User user1 = userOptional.isPresent() ? userOptional.get() : null;
User user2 = userOptional.orElse(null);
User user3 = userOptional.isPresent() ? userOptional.get() : getUser();
User user4 = userOptional.orElseGet(() -> getUser());
if (userOptional.isPresent()) {
System.out.println(userOptional.get());
}
userOptional.ifPresent(System.out::println);
if (userOptional.isPresent()) {
getUser();
}
userOptional.ifPresent(e -> getUser());
List<String> list = null;
if (userOptional.isPresent()) {
list = userOptional.get().getCourseList();
} else {
list = Collections.emptyList();
}
list = userOptional.map(u -> u.getCourseList()).orElse(Collections.emptyList());
getName(new User("xiaoxian"));
getNameNew(new User("xiaoxian"));
}
public static String getName(User user) {
if (user != null) {
String name = user.getName();
if (name != null) {
return name.toUpperCase();
} else {
return null;
}
} else {
return null;
}
}
public static String getNameNew(User user) {
Optional<User> userOptional = Optional.ofNullable(user);
return userOptional.map(u -> u.getName()).map(name -> name.toUpperCase()).orElse(null);
}
}
class User {
public String name;
public List<String> courseList;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<String> getCourseList() {
return courseList;
}
}
|