java8 stream

  • Java 8 中的 Stream 是對集合(Collection)對象功能的增強。
    • 聚合操作、大批量數據操作
    • 與Lambda結合,極大的提高編程效率和程序可讀性
    • 串行和並行兩種模式
    • Stream 的另外一大特點是,數據源本身可以是無限的
  • 流處理的一般過程:數據源(source)→ 數據轉換(轉換成想要的數據)→執行操作獲取想要的結果
  • stream的內部不存儲數據,它只是抓取數據
  • stream也絕不修改底層數據,每次操作都產生一個新的stream
  • 不支持下標索引訪問

常用流操作

  • 流的構成:
    • list.stream():list->stream
    • list.parallelStream()
    • Arrays.stream(new int[]{1,2,3}):array->stream
    • IntStream.range(1,3)
    • Stream.of(1,2,3):多個字段->stream
    • IntStream.concat(stream1,stream2):stream+stream->stream

Intermediate

  • 其目的主要是打開流,做出某種程度的數據映射/過濾,然後返回一個新的流,交給下一個操作使用

  • 這是一個惰性的操作,需要有terminal後纔開始執行

  • 多個轉換操作只會在 Terminal 操作的時候融合起來,一次循環完成。不會出現多次循環

  • 對流排序:stream.sorted((a, b) -> a.getAge() - b.getAge())

  • 對流過濾:stream.filter(a -> a.getAge() > 11)、stream.skip()跳過前幾個元素

  • 對流遍歷:stream.peek()

  • 對流轉換:stream.map()、stream.flatMap()

//把 input Stream 中的層級結構扁平化,就是將流中最底層元素抽出來放到一起
        Stream<List<Integer>> listStream=Stream.of(Arrays.asList(2,3,4),Arrays.asList(2,6,4),Arrays.asList(5,3,4));
        listStream.flatMap(list->list.stream()).forEach(System.out::println);

        Stream<String> stringStream=Stream.of("ddd fdsf dfs fsd fasf dfd","ddd2 321");
        stringStream.flatMap(str->Stream.of(str.split(" "))).forEach(System.out::println);

Terminal

  • 一個流只能有一個 terminal 操作

  • Terminal 操作的執行,纔會真正開始流的遍歷

  • 對流轉換

    • stream.collect(Collectors.toList())
    • stream.collect(Collectors.toCollection(ArrayList::new));
        ArrayList<String> nameList=Stream.of(new String[]{"ming","jia","rui"}).map(str->str+"!!")
                .collect(Collectors.toCollection(ArrayList::new));
        System.out.println(nameList.get(1));  
  • 對流進行聚集
    • findFirst
    • reduce:把 Stream 元素組合起來,進行滾動運算。以下是其衍生出來的簡化方法
      • sum
      • min
      • max
        int max=Stream.of(6,10,3,5,7).reduce(Integer.MIN_VALUE,(a,b)->a>b?a:b);
        System.out.println(max);
       	int total=Stream.of(1,3,5,7).reduce(0,(a,b)->a+b);
        System.out.println(total);
  • 遍歷
    • forEach():如果用了parallelStream,不能保證順序

short-circuiting

  • 輸入一個無限大的數據,但是隻返回一個有限長度數據集,或者在有限時間計算出結果

  • findFirst

  • limit

        Random random=new Random(10);
        int[] nums=random.ints().limit(10).toArray();

Optional

  • 儘可能避免 NullPointerException。
  • 使用 Optional 代碼的可讀性更好
  • Stream 中的 findAny、max/min、reduce 等方法等返回 Optional 值

https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章