
image.png
建立流的方法有很多,常見的如:
從Collection集合建立
根據數值範圍建立數值流
從一系列值
從數組
從檔案
由函數來生成無限流
一、 從Collection集合
Stream stream = new HashSet()
.stream();
Stream stringStream = new ArrayList()
.stream();
二、 根據數值範圍建立數值流
IntStream intStream = IntStream.rangeClosed(1, 100);
三、 從一系列值
Stream提供了一個靜态方法來根據一系列值生成一個流
Stream integerStream = Stream.of(1, 2, 3);
Stream stringStream = Stream.of("喜歡", "天文", "的", "pony", "站長");
AppleStream apple = new AppleStream();
Stream appleStream = Stream.of(apple, apple, apple);
四、 從數組
//重載了支援特定的基本類型流
IntStream intStream = Arrays.stream(new int[]{1, 2, 3});
LongStream longStream = Arrays.stream(new long[]{1L, 2L, 3L});
DoubleStream doubleStream = Arrays.stream(new double[]{1D, 2D, 3D});
Stream stringStream = Arrays.stream(new String[]{"喜歡", "天文", "的", "pony", "站長"});
AppleStream apple = new AppleStream();
Stream appleStream = Arrays.stream(new AppleStream[]{apple, apple, apple});
五、 從檔案
準備檔案

image.png
Stream linesStream = Files.lines(Paths.get("fileStream.txt"));
linesStream.forEach(System.out::println);
結果

image.png
六、由函數來生成無限流
Java8提供了Stream.iterate()和Stream.generate()來生成無限流,這兩個方法會根據給定的表達式來生成包含無限個資料的流,是以一般結合limit()來使用。
疊代: Stream.iterate(T seed,Function apply)
生成: Stream.generate(Supplier s)
// 給定一個初始值seed,和一個`接收一個入參,并帶有傳回值的函數`
Stream.iterate(10, x -> x + 5)
.limit(10)
.forEach(System.out::println);
10
15
20
25
30
35
40
45
50
55
Random random = new Random();
// 接收一個 `無入參,有傳回值` 的函數
Stream.generate(() -> random.nextInt(100))
.limit(10)
.forEach(System.out::println);
60
56
6
61
7
30
97
64
26
54