1 package org.davidmoten.kool.internal.operators.stream; 2 3 import java.util.Optional; 4 5 import org.davidmoten.kool.Maybe; 6 import org.davidmoten.kool.StreamIterable; 7 import org.davidmoten.kool.StreamIterator; 8 import org.davidmoten.kool.function.BiFunction; 9 10 import com.github.davidmoten.guavamini.Preconditions; 11 12 public final class ReduceNoInitialValue<T> implements Maybe<T> { 13 14 private final BiFunction<? super T, ? super T, ? extends T> reducer; 15 private final StreamIterable<T> source; 16 17 public ReduceNoInitialValue(BiFunction<? super T, ? super T, ? extends T> reducer, StreamIterable<T> source) { 18 this.reducer = reducer; 19 this.source = source; 20 } 21 22 @Override 23 public Optional<T> get() { 24 StreamIterator<T> it = source.iteratorNullChecked(); 25 T a, b; 26 if (it.hasNext()) { 27 a = it.nextNullChecked(); 28 } else { 29 return Optional.empty(); 30 } 31 if (it.hasNext()) { 32 b = it.nextNullChecked(); 33 } else { 34 return Optional.empty(); 35 } 36 T v = reducer.applyUnchecked(a, b); 37 while (it.hasNext()) { 38 v = Preconditions.checkNotNull(reducer.applyUnchecked(v, it.nextNullChecked())); 39 } 40 return Optional.of(v); 41 } 42 43 }