什么是Java8 Stream

Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚集操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。

A pipeline is a sequence of aggregate operations. The following example prints the male members contained in the collection roster with a pipeline that consists of the aggregate operations filter and forEach:

管道是一个聚集操作的序列。下面的例子使用包含聚集操作filter和forEach的管道打印包含在roster集合中男性成员的名字:

1
2
3
4
roster
.stream()
.filter(e -> e.getGender() == Person.Sex.MALE)
.forEach(e -> System.out.println(e.getName()));

管道包含如下的组件:

  • 一个源:可以是一个集合、数组、一个生成方法,或者I/O channel。
  • 零个或者多个中间操作。一个中间操作,例如filter,生成一个流。
  • 一个终止操作,一个终止操作例如forEach,产生一个非流结果。例如原始值(如double值),集合,或者在forEach的情况下根本没有任何值。

流是一个元素的序列。不像一个集合,它不是一个数据结构存储元素。相反,一个流通过管道从一个源中提取值。filter操作返回一个包含匹配它断言的要素集的新流。

聚集操作相比于Iterator的不同

  • 使用内部遍历: 聚集操作不包含类似于指示处理集合内的下一个元素的next方法。使用内部委派,你的应用程序确定要迭代的集合,而JDK确定如何迭代该集合。使用外部迭代,你的应用决定它迭代什么集合和它怎样迭代。但是,外部迭代仅仅可以有序的迭代集合的元素。内部迭代没有这个限制,它可以更好的发挥并行计算的优势,它可以将问题分发为子问题,同时解决这些问题,然后将解决子问题方案的结果组合。
  • 从流中处理元素:聚集操作从流中处理元素,不是直接从集合中。因此,它们也称作流操作。
  • 他们支持行为作为参数:对于大多数聚集操作你可以指定lambda表达式作为参数,这允许你自定义一个特定的聚集操作的行为动作。

常用API

  • boolean allMatch(Predicate<? super T> predicate)
    Returns whether all elements of this stream match the provided predicate.
  • boolean anyMatch(Predicate<? super T> predicate)
    Returns whether any elements of this stream match the provided predicate.
  • static <T> Stream.Builder<T> builder()
    Returns a builder for a Stream.
  • <R,A> R collect(Collector<? super T,A,R> collector)
    Performs a mutable reduction operation on the elements of this stream using a Collector.
  • <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
    Performs a mutable reduction operation on the elements of this stream.
  • static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
    Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
  • long count()
    Returns the count of elements in this stream.
  • Stream<T> distinct()
    Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
  • static <T> Stream<T> empty()
    Returns an empty sequential Stream.
  • Stream<T> filter(Predicate<? super T> predicate)
    Returns a stream consisting of the elements of this stream that match the given predicate.
  • Optional<T> findAny()
    Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.
  • Optional<T> findFirst()
    Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.
  • <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
    Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
  • DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)
    Returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
  • IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
    Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
  • LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
    Returns an LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
  • void forEach(Consumer<? super T> action)
    Performs an action for each element of this stream.
  • void forEachOrdered(Consumer<? super T> action)
    Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
  • static <T> Stream<T> generate(Supplier<T> s)
    Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
  • static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
    Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
  • Stream<T> limit(long maxSize)
    Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
  • <R> Stream<R> map(Function<? super T,? extends R> mapper)
    Returns a stream consisting of the results of applying the given function to the elements of this stream.
  • DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
    Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
  • IntStream mapToInt(ToIntFunction<? super T> mapper)
    Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
  • LongStream mapToLong(ToLongFunction<? super T> mapper)
    Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
  • Optional<T> max(Comparator<? super T> comparator)
    Returns the maximum element of this stream according to the provided Comparator.
  • Optional<T> min(Comparator<? super T> comparator)
    Returns the minimum element of this stream according to the provided Comparator.
  • boolean noneMatch(Predicate<? super T> predicate)
    Returns whether no elements of this stream match the provided predicate.
  • static <T> Stream<T> of(T... values)
    Returns a sequential ordered stream whose elements are the specified values.
  • static <T> Stream<T> of(T t)
    Returns a sequential Stream containing a single element.
  • Stream<T> peek(Consumer<? super T> action)
    Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
  • Optional<T> reduce(BinaryOperator<T> accumulator)
    Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
  • T reduce(T identity, BinaryOperator<T> accumulator)
    Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
  • <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator,BinaryOperator<U> combiner)
    Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.
  • Stream<T> skip(long n)
    Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
  • Stream<T> sorted()
    Returns a stream consisting of the elements of this stream, sorted according to natural order.
  • Stream<T> sorted(Comparator<? super T> comparator)
    Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
  • Object[] toArray()
    Returns an array containing the elements of this stream.
  • <A> A[] toArray(IntFunction<A[]> generator)
    Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

参考资料

Java 8 中的 Streams API 详解-陈争云, 占宇剑, 和司磊

Pipelines and Streams

Java™ Platform Standard Ed. 8