// 静态工厂方法,通过value获取Optional对象,value不能为空
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
// 静态工厂方法,通过value获取Optional对象,允许value为空
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
再来看看Optional的成员方法:
(1) public T get()
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
如果在这个Optional中包含这个值,返回值,否则抛出异常:NoSuchElementException。
(2) public boolean isPresent()
public boolean isPresent() {
return value != null;
}
如果值存在则方法会返回true,否则返回 false。
(3) public boolean isPresent()
public boolean isPresent() {
return value != null;
}
如果值存在则方法会返回true,否则返回 false。
(4) public T orElse(T other)
public T orElse(T other) {
return value != null ? value : other;
}
如果存在该值,返回值, 否则返回 other
其他的我就不再分析了,Optional的实现原理非常简单,同时也充分利用了Java8的新特性,如:Function,Predicate,Consumer,使用起来也非常简单,可以很好的解决程序员空指针的头疼问题。
private final String prefix;
private final String delimiter;
private final String suffix;
private StringBuilder value;
private String emptyValue;
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");
}
public StringJoiner(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
Objects.requireNonNull(prefix, "The prefix must not be null");
Objects.requireNonNull(delimiter, "The delimiter must not be null");
Objects.requireNonNull(suffix, "The suffix must not be null");
this.prefix = prefix.toString();
this.delimiter = delimiter.toString();
this.suffix = suffix.toString();
this.emptyValue = this.prefix + this.suffix;
}
定义了prefix(前缀),delimiter(分割符),suffix(后缀),value是存放结果的StringBuilder对象,emptyValue为空结果。
(1) public StringJoiner setEmptyValue(CharSequence emptyValue)
public StringJoiner setEmptyValue(CharSequence emptyValue) {
this.emptyValue = Objects.requireNonNull(emptyValue,
"The empty value must not be null").toString();
return this;
}
设置空值,不能为null,为null将抛出异常。
(2) public StringJoiner add(CharSequence newElement)
public StringJoiner add(CharSequence newElement) {
prepareBuilder().append(newElement);
return this;
}
private StringBuilder prepareBuilder() {
if (value != null) {
value.append(delimiter);
} else {
value = new StringBuilder().append(prefix);
}
return value;
}
拼接字符,可以看到,在拼接字符前先追加分割符。