Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface OptionalMapper<T, R> {
- Optional<R> optionalMap(T t);
- }
- public class Optionals {
- public static <T, R> Optional<R> map(Optional<T> source, Mapper<T,R> f) {
- return source.isPresent() ? new Optional<R>(f.map(source.get())) : Optional.<R>empty();
- }
- public static <T, R> Optional<R> flatMap(Optional<T> source, OptionalMapper<T,R> f) {
- return source.isPresent() ? f.optionalMap(source.get()) : Optional.<R>empty();
- }
- public static <T, R> Optional<R> flatMap(Optional<T> source, FlatMapper<T,R> f) {
- final Optional[] mutableResult = { Optional.<R>empty() };
- if (source.isPresent()) {
- f.flatMapInto(r -> { mutableResult[0] = new Optional(r); }, source.get());
- }
- return mutableResult[0];
- }
- public static <T> Iterable<T> toIterable(final Optional<T> opt) {
- return () -> opt.isPresent() ? new SingleValueIterator<T>(opt.get()) : Optionals.<T>emptyIterator();
- }
- protected static class SingleValueIterator<T> implements Iterator<T> {
- protected T value;
- public SingleValueIterator(T value) {
- this.value = value;
- }
- @Override
- public boolean hasNext() {
- return value != null;
- }
- @Override
- public T next() {
- if (value == null) {
- throw new NoSuchElementException();
- } else {
- final T result = value;
- value = null;
- return result;
- }
- }
- }
- protected static class EmptyIterator<T> implements Iterator<T> {
- @Override
- public boolean hasNext() {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
- @Override
- public T next() {
- throw new NoSuchElementException();
- }
- }
- private final static EmptyIterator<?> EMPTY_ITERATOR = new EmptyIterator<>();
- protected static<T> EmptyIterator<T> emptyIterator() {
- return (EmptyIterator<T>) EMPTY_ITERATOR;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement