Java8 Stream的总结

一. 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包下。这些函数式接口可以有多种分类方式。


2.1 Function

Function是从T到R的一元映射函数。将参数T传递给一个函数,返回R。即R = Function(T)

  
  
  1. @FunctionalInterface

  2. public interface Function<T, R> {

  3.    /**

  4.     * Applies this function to the given argument.

  5.     *

  6.     * @param t the function argument

  7.     * @return the function result

  8.     */

  9.    R apply(T t);

  10.    /**

  11.     * Returns a composed function that first applies the {@code before}

  12.     * function to its input, and then applies this function to the result.

  13.     * If evaluation of either function throws an exception, it is relayed to

  14.     * the caller of the composed function.

  15.     *

  16.     * @param <V> the type of input to the {@code before} function, and to the

  17.     *           composed function

  18.     * @param before the function to apply before this function is applied

  19.     * @return a composed function that first applies the {@code before}

  20.     * function and then applies this function

  21.     * @throws NullPointerException if before is null

  22.     *

  23.     * @see #andThen(Function)

  24.     */

  25.    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {

  26.        Objects.requireNonNull(before);

  27.        return (V v) -> apply(before.apply(v));

  28.    }

  29.    /**

  30.     * Returns a composed function that first applies this function to

  31.     * its input, and then applies the {@code after} function to the result.

  32.     * If evaluation of either function throws an exception, it is relayed to

  33.     * the caller of the composed function.

  34.     *

  35.     * @param <V> the type of output of the {@code after} function, and of the

  36.     *           composed function

  37.     * @param after the function to apply after this function is applied

  38.     * @return a composed function that first applies this function and then

  39.     * applies the {@code after} function

  40.     * @throws NullPointerException if after is null

  41.     *

  42.     * @see #compose(Function)

  43.     */

  44.    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {

  45.        Objects.requireNonNull(after);

  46.        return (T t) -> after.apply(apply(t));

  47.    }

  48.    /**

  49.     * Returns a function that always returns its input argument.

  50.     *

  51.     * @param <T> the type of the input and output objects to the function

  52.     * @return a function that always returns its input argument

  53.     */

  54.    static <T> Function<T, T> identity() {

  55.        return t -> t;

  56.    }

  57. }

Function默认实现了3个default方法,分别是compose、andThen和identity。

方法名对应函数描述
composeV=Function(ParamFunction(T))它体现了嵌套关系
andThenV= ParamFunction(Function(T))转换了嵌套的顺序
identityFunction(T)=T传递自身的函数调用

compose和andThen对于两个函数f和g来说,f.compose(g)等价于g.andThen(f)。

2.2 Predicate

Predicate是一个谓词函数,主要作为一个谓词演算推导真假值存在,返回布尔值的函数。Predicate等价于一个Function的boolean型返回值的子集。

  
  
  1. @FunctionalInterface

  2. public interface Predicate<T> {

  3.    /**

  4.     * Evaluates this predicate on the given argument.

  5.     *

  6.     * @param t the input argument

  7.     * @return {@code true} if the input argument matches the predicate,

  8.     * otherwise {@code false}

  9.     */

  10.    boolean test(T t);

  11.    /**

  12.     * Returns a composed predicate that represents a short-circuiting logical

  13.     * AND of this predicate and another.  When evaluating the composed

  14.     * predicate, if this predicate is {@code false}, then the {@code other}

  15.     * predicate is not evaluated.

  16.     *

  17.     * <p>Any exceptions thrown during evaluation of either predicate are relayed

  18.     * to the caller; if evaluation of this predicate throws an exception, the

  19.     * {@code other} predicate will not be evaluated.

  20.     *

  21.     * @param other a predicate that will be logically-ANDed with this

  22.     *              predicate

  23.     * @return a composed predicate that represents the short-circuiting logical

  24.     * AND of this predicate and the {@code other} predicate

  25.     * @throws NullPointerException if other is null

  26.     */

  27.    default Predicate<T> and(Predicate<? super T> other) {

  28.        Objects.requireNonNull(other);

  29.        return (t) -> test(t) && other.test(t);

  30.    }

  31.    /**

  32.     * Returns a predicate that represents the logical negation of this

  33.     * predicate.

  34.     *

  35.     * @return a predicate that represents the logical negation of this

  36.     * predicate

  37.     */

  38.    default Predicate<T> negate() {

  39.        return (t) -> !test(t);

  40.    }

  41.    /**

  42.     * Returns a composed predicate that represents a short-circuiting logical

  43.     * OR of this predicate and another.  When evaluating the composed

  44.     * predicate, if this predicate is {@code true}, then the {@code other}

  45.     * predicate is not evaluated.

  46.     *

  47.     * <p>Any exceptions thrown during evaluation of either predicate are relayed

  48.     * to the caller; if evaluation of this predicate throws an exception, the

  49.     * {@code other} predicate will not be evaluated.

  50.     *

  51.     * @param other a predicate that will be logically-ORed with this

  52.     *              predicate

  53.     * @return a composed predicate that represents the short-circuiting logical

  54.     * OR of this predicate and the {@code other} predicate

  55.     * @throws NullPointerException if other is null

  56.     */

  57.    default Predicate<T> or(Predicate<? super T> other) {

  58.        Objects.requireNonNull(other);

  59.        return (t) -> test(t) || other.test(t);

  60.    }

  61.    /**

  62.     * Returns a predicate that tests if two arguments are equal according

  63.     * to {@link Objects#equals(Object, Object)}.

  64.     *

  65.     * @param <T> the type of arguments to the predicate

  66.     * @param targetRef the object reference with which to compare for equality,

  67.     *               which may be {@code null}

  68.     * @return a predicate that tests if two arguments are equal according

  69.     * to {@link Objects#equals(Object, Object)}

  70.     */

  71.    static <T> Predicate<T> isEqual(Object targetRef) {

  72.        return (null == targetRef)

  73.                ? Objects::isNull

  74.                : object -> targetRef.equals(object);

  75.    }

  76. }

Predicate的默认方法是and、negate、or。

2.3 Consumer

Consumer是从T到void的一元函数,接受一个入参但不返回任何结果的操作。

  
  
  1. @FunctionalInterface

  2. public interface Consumer<T> {

  3.    /**

  4.     * Performs this operation on the given argument.

  5.     *

  6.     * @param t the input argument

  7.     */

  8.    void accept(T t);

  9.    /**

  10.     * Returns a composed {@code Consumer} that performs, in sequence, this

  11.     * operation followed by the {@code after} operation. If performing either

  12.     * operation throws an exception, it is relayed to the caller of the

  13.     * composed operation.  If performing this operation throws an exception,

  14.     * the {@code after} operation will not be performed.

  15.     *

  16.     * @param after the operation to perform after this operation

  17.     * @return a composed {@code Consumer} that performs in sequence this

  18.     * operation followed by the {@code after} operation

  19.     * @throws NullPointerException if {@code after} is null

  20.     */

  21.    default Consumer<T> andThen(Consumer<? super T> after) {

  22.        Objects.requireNonNull(after);

  23.        return (T t) -> { accept(t); after.accept(t); };

  24.    }

  25. }

Consumer的默认方法是andThen。

2.4 Supplier

Supplier是表示结果的供应者。

  
  
  1. @FunctionalInterface

  2. public interface Supplier<T> {

  3.    /**

  4.     * Gets a result.

  5.     *

  6.     * @return a result

  7.     */

  8.    T get();

  9. }

Supplier的用法:

  
  
  1.        Supplier<String> supplier = new Supplier<String>() {

  2.            @Override

  3.            public String get() {

  4.                return "hello suppiler";

  5.            }

  6.        };

  7.        System.out.println(supplier.get());

或者:

  
  
  1. Supplier<User> userSupplier = User::new;

  2. userSupplier.get();   // new User

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

三. Stream用法

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提高了数据处理效率和开发效率。


关注【Java与Android技术栈】

更多精彩内容请关注扫码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值