Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
stream.map(String::toUpperCase).forEach(System.out::println);
Stream<String> emptyStream = Stream.empty(); ←─使用empty得到一个空流
int[] numbers = {2, 3, 5, 7, 11, 13};
int sum = Arrays.stream(numbers).sum(); ←─总和是4
long uniqueWords = 0;
try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) { ←─流会自动关闭
uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" "))) ←─生成单词流
.distinct() ←─删除重复项
.count(); ←─数一数有多少各不相同的单词
} catch (IOException e) {
←─如果打开文件时出现异常则加以处理
}
Stream.iterate 迭代
# iterate方法生成了一个所有正偶数的流
Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(10);
stream.forEach(System.out::println);
# 斐波纳契元组序列
Stream<int[]> stream = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}).limit(20);
stream.forEach(t -> System.out.println("(" + t[0] + "," + t[1] + ")"));
IntStream.generate 生成
# 生成一个流,其中有五个0到1之间的随机双精度数
Stream<Double> stream = Stream.generate(Math::random).limit(5);
stream.forEach(System.out::println);
# 生成一个全是1的无限流
IntStream ones = IntStream.generate(() -> 1);
list.stream()
-----------------------------------------------------------------------------读书笔记摘自 书名:Java 8实战 作者:[英] Raoul-Gabriel Urma [意] Mario Fusco [英] Alan M 读书笔记 第 5 章 使用流 5.7 构建流