Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Either class using Lightweight Stream API
public final class Either<Left, Right> {
private final Optional<Left> left;
private final Optional<Right> right;
private Either(Optional<Left> left, Optional<Right> right) {
this.left = left;
this.right = right;
}
public static <Left, Right> Either<Left, Right> left(@NonNull Left value) {
return new Either<>(Optional.of(value), Optional.empty());
}
public static <Left, Right> Either<Left, Right> right(@NonNull Right value) {
return new Either<>(Optional.empty(), Optional.of(value));
}
public <T> Either<T, Right> mapLeft(Function<? super Left, ? extends T> func) {
return new Either<>(this.left.map(func), this.right);
}
public <T> Either<Left, T> mapRight(Function<? super Right, ? extends T> func) {
return new Either<>(this.left, this.right.map(func));
}
public void apply(Consumer<? super Left> lConsumer, Consumer<? super Right> rConsumer) {
this.left.ifPresent(lConsumer);
this.right.ifPresent(rConsumer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment