1. 程式人生 > 實用技巧 >021_JDK8.0新特性<四>StreamAPI_2_Stream建立

021_JDK8.0新特性<四>StreamAPI_2_Stream建立

獲取Stream的方式有以下幾種 :

1.集合 :通過Collection系列集合提供的 stream() 或者 parallelStream()

  • Stream<E> stream() :序列操作

  • Stream<E> parallelStream() :並行操作

2.陣列 :通過Arrays中的靜態方法 stream(T[] array) 獲取

  • static <T>Stream<T> stream(T[] array)

3. Stream類中的靜態函式 of()

  • static <T> Stream<T> of(T .... value)

  • static <T> Stream<T> of(T t)

4.建立無限流

  1. 迭代 : static <T>Stream<T> iterate(T seed ,UnaryOperator<T> f)

    • Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 10);
      stream3.limit(10)
                  .forEach(System.out::println);
  2. 生成 : static <T>Stream<T> generate(Supplier<T> s)

    • Stream<Double> stream4 = Stream.generate(() -> Math.random());
      stream4.limit(10)
                  .forEach(System.out::println);