Java Stream

悠遊0902發表於2019-03-31

入門

Java Stream,一個號稱可以極大提升程式設計師開發效率的神器, 一個學會了都不想寫for迴圈的好東西。

本質上是一種函數語言程式設計思維,是將要處理的元素集合看作一種流, 流在管道中傳輸,進行各種操作。

這是官網給出的Stream的特性:

Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements.

Source − Stream takes Collections, Arrays, or I/O resources as input source.

Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.

Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.

Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
複製程式碼

概念

中間操作

(intermediate operation)

呼叫中間操作只會生成一個標記了該操作的新stream,可以繼續執行

中間操作主要包括有:

  • concat()
  • distinct()
  • filter()
  • flatMap()
  • limit()
  • map()
  • peek()
  • skip()
  • sorted()
  • parallel()
  • sequential()
  • unordered()

最終操作

(terminal operation)

元素流在管道中經過中間操作的處理,最後由最終操作得到前面處理的結果。

最終操作主要有:

  • allMatch()
  • anyMatch()
  • collect()
  • count()
  • findAny()
  • findFirst()
  • forEach()
  • forEachOrdered()
  • max()
  • min()
  • noneMatch()
  • reduce()
  • toArray()

使用舉例

查詢最大最小值

    List<T> list = new LinkedList<>();
     ...
     //最小值
    Optional<T> min = 
        list.stream()
            .min(Comparator.comparing(T::getScore));
    if(min.isPresent()){
        T tMin = min.get();
    }
        
    //最大值    
    Optional<T> max =      
        list.stream()
            .max(Comparator.comparing(T::getScore));
    if(max.isPresent()){
        T tMax = t.get();
    }
複製程式碼

遍歷列印

     List<T> list = new LinkedList<>();
     ...
     list.stream()
         .forEach(
                i ->System.out.println(i));
複製程式碼

分頁

     List<T> list = new LinkedList<>();
     ...
    List<T> pagedList = list.stream()
                            .skip(offset)
                            .limit(limit)
                            .collect(Collectors.toList());
複製程式碼

List 轉 Map

下標index為key

List<T> list = new LinkedList<>();
Map<Long, Integer> map = IntStream.range(0, list.size())
                                  .boxed()
                                  .collect(Collectors.toMap(i -> i,i -> list.get(i), (p1,p2)->p1));

複製程式碼

提取List中某欄位

    List<T> list = new LinkedList<>();
    ...
    List<Integer> newList = list.stream()
                                .map(T::getField)
                                .collect(Collectors.toList());
複製程式碼

List<List> to List

    List<List<T>> list = new LinkedList<>();
    ...
    List<Long> collectIds = list.stream()
                                .flatMap(List::stream)
                                .collect(Collectors.toList());
複製程式碼

相關文章