Java8 Stream的總結

Tony沈哲發表於2018-02-19

一. Stream的特性

Stream是Java 8新增的介面,Stream可以認為是一個高階版本的 Iterator。它代表著資料流,流中的資料元素的數量可以是有限的,也可以是無限的。

Stream跟Iterator的差別是

  • 無儲存:Stream是基於資料來源的物件,它本身不儲存資料元素,而是通過管道將資料來源的元素傳遞給操作。
  • 函數語言程式設計:對Stream的任何修改都不會修改背後的資料來源,比如對Stream執行filter操作並不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新的Stream。
  • 延遲執行:Stream的操作由零個或多箇中間操作(intermediate operation)和一個結束操作(terminal operation)兩部分組成。只有執行了結束操作,Stream定義的中間操作才會依次執行,這就是Stream的延遲特性。
  • 可消費性:Stream只能被“消費”一次,一旦遍歷過就會失效。就像容器的迭代器那樣,想要再次遍歷必須重新生成一個新的Stream。

二. Java 8新增的函式式介面

Stream的操作是建立在函式式介面的組合之上的。Java8中新增的函式式介面都在java.util.function包下。這些函式式介面可以有多種分類方式。

Java 8函式式介面的分類.png

Java 8函式式介面第二種分類.png

2.1 Function

Function是從T到R的一元對映函式。將引數T傳遞給一個函式,返回R。即R = Function(T)

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}
複製程式碼

Function預設實現了3個default方法,分別是compose、andThen和identity。

方法名 對應函式 描述
compose V=Function(ParamFunction(T)) 它體現了巢狀關係
andThen V= ParamFunction(Function(T)) 轉換了巢狀的順序
identity Function(T)=T 傳遞自身的函式呼叫

compose和andThen對於兩個函式f和g來說,f.compose(g)等價於g.andThen(f)。

2.2 Predicate

Predicate是一個謂詞函式,主要作為一個謂詞演算推導真假值存在,返回布林值的函式。Predicate等價於一個Function的boolean型返回值的子集。

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}
複製程式碼

Predicate的預設方法是and、negate、or。

2.3 Consumer

Consumer是從T到void的一元函式,接受一個入參但不返回任何結果的操作。

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}
複製程式碼

Consumer的預設方法是andThen。

2.4 Supplier

Supplier是表示結果的供應者。

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
複製程式碼

Supplier的用法:

        Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {
                return "hello suppiler";
            }
        };
        System.out.println(supplier.get());
複製程式碼

或者:

Supplier<User> userSupplier = User::new;
userSupplier.get();   // new User
複製程式碼

Java 8新增了CompletableFuture,它的很多方法的入參都用到了Supplier。

三. Stream用法

Stream操作.png

3.1 Stream的建立

Java 8有多種方式來建立Stream:

  • 通過集合的stream()方法或者parallelStream()
  • 使用流的靜態方法,比如Stream.of(Object[]), IntStream.range(int, int) 或者 Stream.iterate(Object, UnaryOperator)。
  • 通過Arrays.stream(Object[])方法。
  • BufferedReader.lines()從檔案中獲得行的流。
  • Files類的操作路徑的方法,如list、find、walk等。
  • 隨機數流Random.ints()。
  • 其它一些類提供了建立流的方法,如BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), 和 JarFile.stream()。

其實最終都是依賴底層的StreamSupport類來完成Stream建立。

3.2 中間操作

中間操作又可以分為無狀態的(Stateless)和有狀態的(Stateful),無狀態中間操作是指元素的處理不受前面元素的影響,而有狀態的中間操作必須等到所有元素處理之後才知道最終結果。

Stream的中間操作只是一種標記,只有執行了結束操作才會觸發實際計算。 熟悉RxJava、Scala的同學可以看到,Stream中間操作的各個方法在RxJava、Scala中都可以找到熟悉的身影。

3.3 結束操作

3.3.1 短路操作

短路操作是指不用處理全部元素就可以返回結果。短路操作必須一個元素處理一次。

3.3.1 非短路操作

非短路操作可以批量處理資料,但是需要處理完全部元素才會返回結果。

四. 並行流

在建立Stream時,預設是建立序列流。但是可以使用parallelStream()來建立並行流或者parallel()將序列流轉換成並行流。並行流也可以通過sequential()轉換成序列流。

Java 8 Stream的並行流,本質上還是使用Fork/Join模型。

五. 總結

在Java開發中,如果使用了Java 8,那麼強烈建議使用Stream。因為Stream的每個操作都可以依賴Lambda表示式,它是一種宣告式的資料處理方式,並且Stream提高了資料處理效率和開發效率。

相關文章