This repository was archived by the owner on Apr 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOptional.java
More file actions
106 lines (86 loc) · 2.55 KB
/
Optional.java
File metadata and controls
106 lines (86 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package io.reactivex;
import io.reactivex.internal.java.util.Objects;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.functions.Supplier;
import java.util.NoSuchElementException;
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<Object>();
public static <T> Optional<T> of(T value) {
return new Optional<T>(value);
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? Optional.<T>empty() : of(value);
}
private final T value;
private Optional() {
this.value = null;
}
@SuppressWarnings("unchecked")
public static <T> Optional<T> empty() {
return (Optional<T>) EMPTY;
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
public boolean isPresent() {
return value != null;
}
public void ifPresent(Consumer<? super T> consumer) {
if (value != null) {
consumer.accept(value);
}
}
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (isPresent()) {
return predicate.test(value) ? this : Optional.<T>empty();
}
return this;
}
public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (isPresent()) {
return Optional.ofNullable(mapper.apply(value));
}
return empty();
}
public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (isPresent()) {
return Objects.requireNonNull(mapper.apply(value));
}
return empty();
}
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 {
if (value == null) {
throw exceptionSupplier.get();
}
return value;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Optional)) return false;
Optional<?> other = (Optional<?>) o;
return Objects.equals(value, other.value);
}
@Override public int hashCode() {
return Objects.hashCode(value);
}
@Override public String toString() {
return value == null ? "Optional.empty" : "Optional[" + value + ']';
}
}