Advertisement
Guest User

JDK8 Optionals

a guest
Nov 1st, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. public interface OptionalMapper<T, R> {
  2.     Optional<R> optionalMap(T t);
  3. }
  4.  
  5. public class Optionals {
  6.     public static <T, R> Optional<R> map(Optional<T> source, Mapper<T,R> f) {
  7.         return source.isPresent() ? new Optional<R>(f.map(source.get())) : Optional.<R>empty();
  8.     }
  9.  
  10.     public static <T, R> Optional<R> flatMap(Optional<T> source, OptionalMapper<T,R> f) {
  11.         return source.isPresent() ? f.optionalMap(source.get()) : Optional.<R>empty();
  12.     }
  13.  
  14.     public static <T, R> Optional<R> flatMap(Optional<T> source, FlatMapper<T,R> f) {
  15.         final Optional[] mutableResult = { Optional.<R>empty() };
  16.  
  17.         if (source.isPresent()) {
  18.             f.flatMapInto(r -> { mutableResult[0] = new Optional(r); }, source.get());
  19.         }
  20.  
  21.         return mutableResult[0];
  22.     }
  23.  
  24.     public static <T> Iterable<T> toIterable(final Optional<T> opt) {
  25.         return () -> opt.isPresent() ? new SingleValueIterator<T>(opt.get()) : Optionals.<T>emptyIterator();
  26.     }
  27.  
  28.     protected static class SingleValueIterator<T> implements Iterator<T> {
  29.         protected T value;
  30.  
  31.         public SingleValueIterator(T value) {
  32.             this.value = value;
  33.         }
  34.  
  35.         @Override
  36.         public boolean hasNext() {
  37.             return value != null;
  38.         }
  39.  
  40.         @Override
  41.         public T next() {
  42.             if (value == null) {
  43.                 throw new NoSuchElementException();
  44.             } else {
  45.                 final T result = value;
  46.                 value = null;
  47.                 return result;
  48.             }
  49.         }
  50.     }
  51.  
  52.     protected static class EmptyIterator<T> implements Iterator<T> {
  53.         @Override
  54.         public boolean hasNext() {
  55.             return false;  //To change body of implemented methods use File | Settings | File Templates.
  56.         }
  57.  
  58.         @Override
  59.         public T next() {
  60.             throw new NoSuchElementException();
  61.         }
  62.     }
  63.  
  64.     private final static EmptyIterator<?> EMPTY_ITERATOR = new EmptyIterator<>();
  65.  
  66.     protected static<T> EmptyIterator<T> emptyIterator() {
  67.         return (EmptyIterator<T>) EMPTY_ITERATOR;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement