All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.gwt.emul.java.util.stream.Stream Maven / Gradle / Ivy

There is a newer version: 2.12.1
Show newest version
/*
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package java.util.stream;

import static javaemul.internal.InternalPreconditions.checkState;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.Spliterators.AbstractSpliterator;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.function.UnaryOperator;

/**
 * See 
 * the official Java API doc for details.
 *
 * @param  the type of data being streamed
 */
public interface Stream extends BaseStream> {

  /**
   * See 
   * the official Java API doc for details.
   */
  interface Builder extends Consumer {
    @Override
    void accept(T t);

    default Stream.Builder add(T t) {
      accept(t);
      return this;
    }

    Stream build();
  }

  static  Stream.Builder builder() {
    return new Builder() {
      private Object[] items = new Object[0];

      @Override
      public void accept(T t) {
        checkState(items != null, "Builder already built");
        items[items.length] = t;
      }

      @Override
      @SuppressWarnings("unchecked")
      public Stream build() {
        checkState(items != null, "Builder already built");
        Stream stream = (Stream) Arrays.stream(items);
        items = null;
        return stream;
      }
    };
  }

  static  Stream concat(Stream a, Stream b) {
    // This is nearly the same as flatMap, but inlined, wrapped around a single spliterator of
    // these two objects, and without close() called as the stream progresses. Instead, close is
    // invoked as part of the resulting stream's own onClose, so that either can fail without
    // affecting the other, and correctly collecting suppressed exceptions.

    // TODO replace this flatMap-ish spliterator with one that directly combines the two root
    // streams
    Spliterator> spliteratorOfStreams =
        Arrays.asList(a, b).spliterator();

    AbstractSpliterator spliterator =
        new Spliterators.AbstractSpliterator(Long.MAX_VALUE, 0) {
          Spliterator next;

          @Override
          public boolean tryAdvance(Consumer action) {
            // look for a new spliterator
            while (advanceToNextSpliterator()) {
              // if we have one, try to read and use it
              if (next.tryAdvance(action)) {
                return true;
              } else {
                // failed, null it out so we can find another
                next = null;
              }
            }
            return false;
          }

          private boolean advanceToNextSpliterator() {
            while (next == null) {
              if (!spliteratorOfStreams.tryAdvance(
                  n -> {
                    if (n != null) {
                      next = n.spliterator();
                    }
                  })) {
                return false;
              }
            }
            return true;
          }
        };

    Stream result = new StreamImpl(null, spliterator);

    return result.onClose(a::close).onClose(b::close);
  }

  static  Stream empty() {
    return new StreamImpl.Empty(null);
  }

  static  Stream generate(Supplier s) {
    AbstractSpliterator spliterator =
        new Spliterators.AbstractSpliterator(
            Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.ORDERED) {
          @Override
          public boolean tryAdvance(Consumer action) {
            action.accept(s.get());
            return true;
          }
        };
    return StreamSupport.stream(spliterator, false);
  }

  static  Stream iterate(T seed, UnaryOperator f) {
    return iterate(seed, ignore -> true, f);
  }

  static  Stream iterate(T seed, Predicate hasNext, UnaryOperator f) {
    AbstractSpliterator spliterator =
        new Spliterators.AbstractSpliterator(
            Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.ORDERED) {
          private boolean first = true;
          private T next = seed;
          private boolean terminated = false;

          @Override
          public boolean tryAdvance(Consumer action) {
            if (terminated) {
              return false;
            }
            if (!first) {
              next = f.apply(next);
            }
            first = false;

            if (!hasNext.test(next)) {
              terminated = true;
              return false;
            }
            action.accept(next);
            return true;
          }
        };
    return StreamSupport.stream(spliterator, false);
  }

  static  Stream of(T t) {
    // TODO consider a splittable that returns only a single value, either for use here or in the
    //      singleton collection types
    return Collections.singleton(t).stream();
  }

  static  Stream of(T... values) {
    return Arrays.stream(values);
  }

  static  Stream ofNullable(T t) {
    if (t == null) {
      return empty();
    } else {
      return of(t);
    }
  }

  boolean allMatch(Predicate predicate);

  boolean anyMatch(Predicate predicate);

   R collect(Collector collector);

   R collect(
      Supplier supplier, BiConsumer accumulator, BiConsumer combiner);

  long count();

  Stream distinct();

  default Stream dropWhile(Predicate predicate) {
    Spliterator prev = spliterator();
    Spliterator spliterator =
        new Spliterators.AbstractSpliterator(prev.estimateSize(),
                prev.characteristics() & ~(Spliterator.SIZED | Spliterator.SUBSIZED)) {
          private boolean drop = true;
          private boolean found;

          @Override
          public boolean tryAdvance(Consumer action) {
            found = false;
            if (drop) {
              // drop items until we find one that matches
              while (drop && prev.tryAdvance(item -> {
                if (!predicate.test(item)) {
                  drop = false;
                  found = true;
                  action.accept(item);
                }
              })) {
                // do nothing, work is done in tryAdvance
              }
              // only return true if we accepted at least one item
              return found;
            } else {
              // accept one item, return result
              return prev.tryAdvance(action);
            }
          }
        };
    return StreamSupport.stream(spliterator, false);
  }

  Stream filter(Predicate predicate);

  Optional findAny();

  Optional findFirst();

   Stream flatMap(Function> mapper);

  DoubleStream flatMapToDouble(Function mapper);

  IntStream flatMapToInt(Function mapper);

  LongStream flatMapToLong(Function mapper);

  void forEach(Consumer action);

  void forEachOrdered(Consumer action);

  Stream limit(long maxSize);

   Stream map(Function mapper);

  DoubleStream mapToDouble(ToDoubleFunction mapper);

  IntStream mapToInt(ToIntFunction mapper);

  LongStream mapToLong(ToLongFunction mapper);

  Optional max(Comparator comparator);

  Optional min(Comparator comparator);

  boolean noneMatch(Predicate predicate);

  Stream peek(Consumer action);

  Optional reduce(BinaryOperator accumulator);

  T reduce(T identity, BinaryOperator accumulator);

   U reduce(U identity, BiFunction accumulator, BinaryOperator combiner);

  Stream skip(long n);

  Stream sorted();

  Stream sorted(Comparator comparator);

  default Stream takeWhile(Predicate predicate) {
    Spliterator original = spliterator();
    Spliterator spliterator =
        new Spliterators.AbstractSpliterator(original.estimateSize(),
                original.characteristics() & ~(Spliterator.SIZED | Spliterator.SUBSIZED)) {
          private boolean take = true;
          private boolean found;

          @Override
          public boolean tryAdvance(Consumer action) {
            found = false;
            if (!take) {
              // already failed the check
              return false;
            }
            original.tryAdvance(item -> {
              if (predicate.test(item)) {
                found = true;
                action.accept(item);
              } else {
                take = false;
              }
            });
            return found;
          }
        };
    return StreamSupport.stream(spliterator, false);
  }

  Object[] toArray();

   A[] toArray(IntFunction generator);
}