Stream雖然繼承了AutoCloseable接口,但是不會(huì)自動(dòng)close荷腊,除非在try-with-resource里面
每次中間操作都會(huì)返回一個(gè)新的stream
flatMap在執(zhí)行一次之后會(huì)關(guān)閉stream
第一種:
List<String> collection = new ArrayList<>();
collection.stream();
第二種:
String[] array = {"1"};
Arrays.stream(array);
第三種:
Stream.of(new Object()); 對(duì)象
Stream.of(1 ,2 ,3); 可變參數(shù)
Stream.of(array); 數(shù)組
generate(Supplier<T> s)
iterate(起始值艳悔,F(xiàn)unction<T> f)
Stream<String> echos = Stream.generate(() -> "echo");
Stream<Integer> integers = Stream.iterate(0, num -> num + 1);
但是這些都是中間操作,不會(huì)真的被執(zhí)行女仰,直到遇到終端操作
第一次不會(huì)執(zhí)行猜年,直接返回起始值,所以假設(shè) .limit(10)疾忍,其實(shí)只執(zhí)行了9次
中間操作包括:filter skip limit map
- Collector 和 Collectors 區(qū)別
Collector: 是一個(gè) interface
Collectors: 是一個(gè)final class乔外,工具類,通過靜態(tài)方法生成各種常用的 Collector
collect() 操作會(huì)把其接收的元素聚集(aggregate)到一起
方法引用類別 |
舉例 |
引用靜態(tài)方法 |
Integer::sum |
引用某個(gè)對(duì)象的實(shí)例方法 |
list::add |
引用特定類型任意對(duì)象的實(shí)例方法 |
String::length |
引用構(gòu)造方法 |
HashMap::new |