1.1 目标
1.2 Stream常用方法
Stream流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:
终结方法:返回值类型不再是 Stream 类型的方法,不再支持链式调用。本小节中,终结方法包括 count 和
forEach 方法。
非终结方法:返回值类型仍然是 Stream 类型的方法,支持链式调用。(除了终结方法外,其余方法均为非终结
方法。)
备注:本小节之外的更多方法,请自行参考API文档。
1.3 Stream注意事项(重要)
1. Stream只能操作一次
2. Stream方法返回的是新的流
3. Stream不调用终结方法,中间的操作不会执行
package com.itheima.demo05stream;
import java.util.stream.Stream;
public class Demo03StreamNotice {
public static void main(String[] args) {
Stream<String> stream = Stream.of("aa", "bb", "cc");
// 1. Stream只能操作一次
long count = stream.count();
long count2 = stream.count();
// 2. Stream方法返回的是新的流
Stream<String> limit = stream.limit(1);
System.out.println("stream" + stream);
System.out.println("limit" + limit);
// 3. Stream不调用终结方法,中间的操作不会执行
stream.filter((s) -> {
System.out.println(s);
return true;
}).count();
}
}
1.4 小结
我们学习了Stream的常用方法,我们知道Stream这些常用方法可以分成两类,终结方法,函数拼接方法
Stream的3个注意事项:
1. Stream只能操作一次
2. Stream方法返回的是新的流
3. Stream不调用终结方法,中间的操作不会执行