[Java 8] Optional class and functional programming
Usage of the Optional class
Java's Optional class is used to handle situations where there may be an empty value. It was introduced in Java 8 to reduce the occurrence of Null Pointer Exceptions.
Usually we use if to judge whether the object is null, and then do some processing, but this is not elegant. as follows:
List<String> list = new ArrayList<>();
// 常规方法
if(list != null){
List<String> new_list = new ArrayList<>();
for(String s : list){
if("".equals(s)) continue;
new_list.add(s);
}
return new_list;
}else{
return null
}
// 优雅写法 使用Optional + 函数式编程
return Optional.ofNullable(list)
.filter(s -> !"".equals(s))
.orElse(null);
Common methods of the Optional class
Create an Optional object:
Optional<T> optionalValue = Optional.of(value); // 值不能为空
Optional<T> optionalNullableValue = Optional.ofNullable(nullableValue); // 值可以为空
Optional<T> optionalEmpty = Optional.empty(); // 创建一个空的 Optional 对象
Determine whether an Optional object contains a value:
optionalValue.isPresent(); // 返回 true,如果值存在
Get the value in the Optional object:
T value = optionalValue.get(); // 若值存在,则获取该值,否则抛出 NoSuchElementException 异常
Check and take action:
optionalValue.ifPresent(val -> {
// 如果值存在,则执行操作
});
Use default values:
T value = optionalValue.orElse(defaultValue); // 如果值存在,则返回该值,否则返回默认值
T value = optionalValue.orElseGet(() -> {
// 如果值不存在,则执行自定义操作生成默认值
});
Other methods:
optionalValue.map(val -> {
// 对值进行映射转换操作
});
optionalValue.filter(val -> {
// 过滤值的条件
});
optionalValue.flatMap(val -> {
// 针对嵌套 Optional 进行操作
});
When using the Optional class, it is mainly used in conjunction with functional programming methods: Consumer, Predicate, and Function classes.
Optional.ifPresent and Consumer class
Observe the source code of Optional.ifPresent:
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
Consumer is a functional interface that represents an operation that takes one input parameter and returns no result. It is usually used to perform some operations on the given parameters, such as modifying the state of the object, printing information, etc.
The Consumer interface contains an abstract method void accept(T t), which accepts a parameter of type T and operates on it.
Optional.ifPresent sample code:
java
Optional.ofNullable(user).ifPresent(o -> {
// ifPresent确定是否有值 之后进行赋值或打印等无return操作
o.setName("...");
System.out.println(o);
}));
Optional.filter and Predicate class
Observe the source code of Optional.filter:
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Predicate is a functional interface that represents an assertion (judgment condition), accepts an input parameter and returns a Boolean value. It is usually used to filter collections or verify the legality of input parameters.
The Predicate interface contains an abstract method boolean test(T t), which accepts a parameter of type T and returns a Boolean value indicating the result of the judgment.
Optional.filter sample code:
java
Optional.ofNullable(str).filter(o -> !"".equals(o) );
Optional.map and Function class
Observe the source code of Optional.map:
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));
}
}
Function<T, R> is a functional interface that represents an operation that takes one input parameter and returns one result. It is usually used to transform one value into another, or to perform some complex calculations.
The Function interface contains an abstract method R apply(T t), which accepts a parameter of type T and returns a result of type R.
Optional.map sample code:
java
Optional.ofNullable(str).map(o -> {
// 进行一些操作 然后return数据
return str;
} );