函數語言程式設計 - 固定長度流
有多種方法可用於建立固定長度流。
使用 Stream.of() 方法
使用 Collection.stream() 方法
使用 Stream.builder() 方法
以下示例展示上述所有方法來建立固定長度流。
示例 - 固定長度流
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class FunctionTester {
public static void main(String[] args) {
System.out.println("Stream.of():");
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.forEach(System.out::println);
System.out.println("Collection.stream():");
Integer[] numbers = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(numbers);
list.stream().forEach(System.out::println);
System.out.println("StreamBuilder.build():");
Stream.Builder<Integer> streamBuilder = Stream.builder();
streamBuilder.accept(1);
streamBuilder.accept(2);
streamBuilder.accept(3);
streamBuilder.accept(4);
streamBuilder.accept(5);
streamBuilder.build().forEach(System.out::println);
}
}
輸出
Stream.of(): 1 2 3 4 5 Collection.stream(): 1 2 3 4 5 StreamBuilder.build(): 1 2 3 4 5
廣告