0. 强调‘面对对象编程’的封装类
java.util.Optional java lambda 表达式的局部变量为什么必须是final修饰?
gitee中的simple code
不得不说,这一块guava做了不少有意思的事情…
1. 走读源码的同时也会领悟到其中的用心
package java.util;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>();
private final T value;
private Optional() {this.value = null;}
private Optional(T value) {this.value = Objects.requireNonNull(value);}
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
public static <T> Optional<T> of(T value) {return new Optional<>(value);}
public static <T> Optional<T> ofNullable(T value) {return value == null ? empty() : of(value);}
public void ifPresent(Consumer<? super T> consumer) {if (value != null)consumer.accept(value);}
public Optional<T> filter(Predicate<? super T> predicate) {...}
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {...}
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {...}
public T orElse(T other) {return value != null ? value : other;}
public T orElseGet(Supplier<? extends T> other) {return value != null ? value : other.get();}
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {...}
@Override
public boolean equals(Object obj) {...}
@Override
public int hashCode() {return Objects.hashCode(value);}
@Override
public String toString() {return value != null ? String.format("Optional[%s]", value) : "Optional.empty";}
public boolean isPresent() {return value != null;}
public T get() {...}
}
2. simple code
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class TestOptional {
private static List<Integer> out;
public static void main(String[] args) {
final List<Integer> in = Arrays.asList(1,-6,null,218,23,1,null,-33);
dealProblem(in);
Consumer c = list -> System.err.println(list);
c.accept(obtainOut());
}
private final static void dealProblem(final List<Integer> in){
Optional
.ofNullable(in)
.ifPresent(
inTmp -> {
out = inTmp
.stream()
.filter(Objects::nonNull)
.map(Math::abs)
.collect(
Collectors.toList()
)
;
}
)
;
}
private final static List<Integer> obtainOut(){
return Optional
.ofNullable(out)
.orElse(Lists.newArrayList())
;
}
}
|