如何在 Java 9 中使用 Stream API 中的 collect() 方法?


Stream API 中的 collect() 方法從流物件收集所有物件,並存儲在 集合中。使用者必須指定結果儲存的集合型別。我們使用 Collectors Enum 指定集合型別。Collectors Enum 中存在不同的型別和不同的操作,但大多數時候我們可以使用 Collectors.toList()Collectors.toSet()Collectors.toMap()

語法

<R, A> R collect(Collector<? super T,A,R> collector)

示例

import java.util.*;
import java.util.stream.*;

public class StreamCollectMethodTest {
   public static void main(String args[]) {
      List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");

      List<String> subset1 = list.stream()
                                 .takeWhile(s -> !s.equals("e"))
                                 .collect(Collectors.toList());
      System.out.println(subset1);

      List<String> subset2 = list.stream()
                                 .dropWhile(s -> !s.equals("e"))
                                 .collect(Collectors.toList());
      System.out.println(subset2);

      List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i+1)
                                    .collect(Collectors.toList());
      System.out.println(numbers);
   }
}

輸出

[a, b, c, d]
[e, f, g, h, i]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

更新於: 27-Feb-2020

1K+ 次瀏覽

開啟您的 事業

完成課程獲取認證

開始
廣告