Optional, Guava and Java 8

public abstract class Optional<T> implements Serializable { 
public abstract boolean isPresent();
public abstract T get();
public abstract T or(T defaultValue);
....
}
final class Absent extends Optional<Object> { .... } 
final class Present<T> extends Optional<T> { .... }
public static <T> Optional<T> of(T value) { 
return new Present<T>(checkNotNull(value));
}
public static <T> Optional<T> fromNullable(@Nullable T value) { return (value == null) ? Optional<T>.absent() : new Present<T>(value);
}
@Override 
public boolean isPresent() {
return false;
}
@Override
public Object get() {
throw new IllegalStateException("value is absent");
}
public boolean isPresent() { 
return value != null;
}
@Override 
public boolean isPresent() {
return true;
}
@Override
public T get() {
return value;
}
@Override 
public int hashCode() {
return 0x598df91c + value.hashCode();
}
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 boolean isPresent() { 
return value != null;
}
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
public Optional<T> filter(Predicate<? super T> predicate) public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
@Override 
public int hashCode() {
return Objects.hashCode(value);
}
@Nullable private final String flightNumber; public Optional<String> getFlightNumber() { 
return Optional.ofNullable(this.flightNumber)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Edouard Kaiser

Edouard Kaiser

Senior Engineering Manager @Atlassian, technology lover, Java engineer originally, distributed systems aficionado and team builder.