最近在學習Java8的新特性,在學習到Stream API時,知道使用Stream需要三個操作步驟:建立Stream、中間操作以及終止操作。今天記錄一下建立Stream的幾種方式:
1. 通過Collection系列集合的stream方法:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.stream().forEach(System.out::println);
2. 通過Arrays.stream方法:
String[] array = {"aa", "bb", "cc"};
Arrays.stream(array)
.forEach(System.out::println);
3. 通過Stream的of方法:
Stream.of(1, 2, 3, 4, 5)
.forEach(System.out::println);
4. 建立無限流
//4.1 疊代方式
Stream.iterate(0, x -> x + 2)
.limit(10) //limit就是中間操作
.forEach(System.out::println);
//4.2 生成方式
Stream.generate(() -> Math.random())
.limit(10)
.forEach(System.out::println);
//因為stream操作是延遲的,這就意味着它們會等到需要結果的時候才執行,以上的forEach實際上就是終止操作,隻有有終止操作,流的相關操作才會執行。
以上相關内容參考尚矽谷Java8新特性教學視訊