Java8 Stream的總結

一. Stream的特性

Stream是Java 8新增的接口,Stream能夠認爲是一個高級版本的 Iterator。它表明着數據流,流中的數據元素的數量能夠是有限的,也能夠是無限的。java

Stream跟Iterator的差異是編程

  • 無存儲:Stream是基於數據源的對象,它自己不存儲數據元素,而是經過管道將數據源的元素傳遞給操做。
  • 函數式編程:對Stream的任何修改都不會修改背後的數據源,好比對Stream執行filter操做並不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新的Stream。
  • 延遲執行:Stream的操做由零個或多箇中間操做(intermediate operation)和一個結束操做(terminal operation)兩部分組成。只有執行告終束操做,Stream定義的中間操做纔會依次執行,這就是Stream的延遲特性。
  • 可消費性:Stream只能被「消費」一次,一旦遍歷過就會失效。就像容器的迭代器那樣,想要再次遍歷必須從新生成一個新的Stream。

二. Java 8新增的函數式接口

Stream的操做是創建在函數式接口的組合之上的。Java8中新增的函數式接口都在java.util.function包下。這些函數式接口能夠有多種分類方式。app

Java 8函數式接口的分類.png

Java 8函數式接口第二種分類.png

2.1 Function

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

@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。dom

方法名 對應函數 描述
compose V=Function(ParamFunction(T)) 它體現了嵌套關係
andThen V= ParamFunction(Function(T)) 轉換了嵌套的順序
identity Function(T)=T 傳遞自身的函數調用

compose和andThen對於兩個函數f和g來講,f.compose(g)等價於g.andThen(f)。ide

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的一元函數,接受一個入參但不返回任何結果的操做。ui

@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。this

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提升了數據處理效率和開發效率。

相關文章
相關標籤/搜索