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.10.0
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) {
    AbstractSpliterator spliterator =
        new Spliterators.AbstractSpliterator(
            Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.ORDERED) {
          private T next = seed;

          @Override
          public boolean tryAdvance(Consumer action) {
            action.accept(next);
            next = f.apply(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);
  }

  boolean allMatch(Predicate predicate);

  boolean anyMatch(Predicate predicate);

   R collect(Collector collector);

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

  long count();

  Stream distinct();

  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);

  Object[] toArray();

   A[] toArray(IntFunction generator);
}