Java8 Streams API 學習筆記

主要的使用/處理對象(數據源):

數組、列表等集合(Collection)對象,比如:
代碼1:

// 1. Individual values
Stream stream = Stream.of("a", "b", "c");

// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);

// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();

// 4. Int Stream
IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);

不過,Steam的數據源本身可以是無限的,比如Stream Generator、IO channel(例如java.io.BufferedReader.lines())等等……

Stream的主要功能:

  • 聚合操作(aggregate operation)
  • 大批量數據操作 (bulk data operation)

例如:
- 求平均值
- 求最大值
- 篩選(去除無效記錄、按條件過濾、等)
- 排序

這些操作不會修改原來的Stream,而是生成新的;並且支持多線程並行處理。
一個簡單的例子:
代碼2:

List<Integer> transactionsIds =
    transactions.parallelStream(). //支持並行操作的流
    filter(t -> t.getType() == Transaction.GROCERY). //篩選
    sorted(comparing(Transaction::getValue).reversed()). //排序
    map(Transaction::getId). //映射(投影)操作,只選取id
    collect(toList()); //生成一個新的集合

簡單地說,對Stream的使用就是實現一個 filter-map-reduce 過程,產生一個最終結果,或者導致一個副作用(side effect)。

Stream和Iterator的異同:

相同之處:

  • 都是用來遍歷和處理數組和列表等集合
  • 都只能是單向的遍歷

不同之處:

  • Stream可以並行地利用多線程操作;而Iterator只能單線程操作
  • Stream支持的數據源比Iterator多

Stream轉換爲其他數據結構的方法:

代碼3:

// 1. Array
String[] strArray1 = stream.toArray(String[]::new);

// 2. Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));

// 3. String
String str = stream.collect(Collectors.joining()).toString();

// 4. toMap
Map<Integer, Integer> map = stream.collect(
    Collectors.toMap(
        e -> e.get("key"),
        e -> e.get("value")
    )
);

可見,主要是toArray()和collect()兩個方法。

Stream的操作類型:

  • Intermediate: 一個流可以後面跟隨零個或多個 intermediate 操作。其目的主要是打開流,做出某種程度的數據映射/過濾,然後返回一個新的流,交給下一個操作使用。這類操作都是惰性化的(lazy),就是說,僅僅調用到這類方法,並沒有真正開始流的遍歷。
  • Terminal: 一個流只能有一個 terminal 操作,當這個操作執行後,流就被使用“光”了,無法再被操作。所以這必定是流的最後一個操作。Terminal 操作的執行,纔會真正開始流的遍歷,並且會生成一個結果,或者一個 side effect。
  • short-circuiting:
    • 對於一個intermediate操作,如果它接受的是一個無限大(infinite/unbounded)的 Stream,但返回一個有限的新 Stream。
    • 對於一個terminal操作,如果它接受的是一個無限大的Stream,但能在有限的時間計算出結果。

那麼,對一個Stream進行多次Intermediate操作,是不是需要執行多次for循環?
不是的。因爲Intermediate操作是lazy的,多個這樣的操作只會在Terminal操作的時候才融合起來,在一次循環中就可以完成了。

常見的操作可以歸類:

  • Intermediate:
    map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
  • Terminal:
    forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
  • Short-circuiting:
    anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
各種操作的實例:

map/flatMap: 映射、投影
代碼4

//字符串列表轉換成大寫:
List<String> output = wordList.stream().
    map(String::toUpperCase).
    collect(Collectors.toList());

//整數轉換爲平方數:
List<Integer> nums = Arrays.asList(1, 2, 3, 4);
List<Integer> squareNums = nums.stream().
    map(n -> n * n).
    collect(Collectors.toList());

//把多個List合併成一個List:
Stream<List<Integer>> inputStream = Stream.of(
    Arrays.asList(1),
    Arrays.asList(2, 3),
    Arrays.asList(4, 5, 6)
 );
Stream<Integer> outputStream = inputStream.
    flatMap((childList) -> childList.stream());

filter: 篩選、過濾
代碼5

//只留下偶數:
Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens =
    Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);

//從文件中獲取所有單詞
List<String> output = reader.lines(). //數據來源,可以是文件的reader
    flatMap(line -> Stream.of(line.split(REGEXP))). //對每行拆分出單詞
    filter(word -> word.length() > 0). //過濾掉無效的單詞
    collect(Collectors.toList());

forEach: 接收一個Lambda表達式,然後在Stream的每一個元素上執行該表達式
代碼6

//從花名冊中篩選出男性然後打印出來
roster.stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .forEach(p -> System.out.println(p.getName()));

注意: forEach是terminal操作,如果要對Stream做多次輸出操作,可以使用peek(偷窺)代替:
代碼7

//peek對每個元素執行操作並返回一個新的 Stream
Stream.of("one", "two", "three", "four")
 .filter(e -> e.length() > 3)
 .peek(e -> System.out.println("Filtered value: " + e))
 .map(String::toUpperCase)
 .peek(e -> System.out.println("Mapped value: " + e))
 .collect(Collectors.toList());

reduce: 把Stream中的元素組合起來
  它接收一個起始值(種子,第一個參數),然後依照運算規則(BinaryOperator),和前面 Stream 的第一個、第二個、第n個元素組合。字符串拼接、數值的sum、min、max、average都是特殊的reduce。例如Stream的sum就相當於
  Integer sum = integers.reduce(0, (a, b) -> a+b); 或
  Integer sum = integers.reduce(0, Integer::sum);
  也有沒有起始值的情況,這時會把Stream的前面兩個元素組合起來,返回的是Optional對象。
代碼8

// 字符串連接,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat); 

// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min); 

// 求和,sumValue = 10, 有起始值
int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);

// 求和,sumValue = 10, 無起始值,這裏reduce返回的是Optional,需要get()一下
sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get(); 

// 過濾,字符串連接,concat = "ace"
concat = Stream.of("a", "B", "c", "D", "e", "F").
 filter(x -> x.compareTo("Z") > 0).
 reduce("", String::concat);

limit/skip: 返回Stream的前面n個元素 / 扔掉前n個元素
代碼9

List<String> personList2 = persons.stream()
    .map(Person::getName)
    .limit(10)
    .skip(3)
    .collect(Collectors.toList());
System.out.println(personList2);

sorted: 排序
代碼10

List<Person> personList2 = persons.stream()
    .limit(2)
    .sorted((p1, p2)->p1.getName().compareTo(p2.getName()))
    .collect(Collectors.toList());
System.out.println(personList2);

min/max/distinct 找出最小、最大、排除重複
代碼11

//找出最長的一行:
BufferedReader br = new BufferedReader(new FileReader("c:\\SUService.log"));
int longest = br.lines().
 mapToInt(String::length).
 max().
 getAsInt();
br.close();
System.out.println(longest);

// 找出全文的單詞,合併重複的,轉小寫,並排序
List<String> words = br.lines().
 flatMap(line -> Stream.of(line.split(" "))).
 filter(word -> word.length() > 0).
 map(String::toLowerCase).
 distinct().
 sorted().
 collect(Collectors.toList());
br.close();
System.out.println(words);

match:allMatch/anyMatch/noneMatch 根據是否match返回true/false
代碼12

boolean isAllAdult = persons.stream().
    allMatch(p -> p.getAge() > 18);

boolean isThereAnyChild = persons.stream().
    anyMatch(p -> p.getAge() < 12);
其他高級操作:

generate/Supplier/iterate 生成一個流:
代碼13

//生成100~100之間的隨機數:
IntStream.generate(() -> (int) (System.nanoTime() % 100)).
    limit(10).
    forEach(System.out::println);

//生成一個有10個Person對象的流
Stream.generate(new PersonSupplier()).
    limit(10).
    forEach(p -> System.out.println(p.getName() + ", " + p.getAge()));

private class PersonSupplier implements Supplier<Person> {
    private int index = 0;
    private Random random = new Random();

    @Override
    public Person get() {
        return new Person(index++, "StormTestUser" + index, random.nextInt(100));
    }
}

//生成一個等差數列
Stream.iterate(0, n -> n + 3).limit(10). forEach(x -> System.out.print(x + " "));

groupingBy/partitioningBy 分組/歸組:
代碼14

//按照年齡歸組:
Map<Integer, List<Person>> personGroups = 
    Stream.generate(new PersonSupplier()).
    limit(100).
    collect(Collectors.groupingBy(Person::getAge));

//按照是否小於18歲進行分組:
Map<Boolean, List<Person>> children = 
    Stream.generate(new PersonSupplier()).
    limit(100).
    collect(Collectors.partitioningBy(p -> p.getAge() < 18));
發佈了201 篇原創文章 · 獲贊 397 · 訪問量 204萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章