1.1 目标


了解Stream常用方法的分类
掌握Stream注意事项


1.2 Stream常用方法


Stream流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:

image.png

终结方法:返回值类型不再是 Stream 类型的方法,不再支持链式调用。本小节中,终结方法包括 count 和 forEach 方法。

非终结方法:返回值类型仍然是 Stream 类型的方法,支持链式调用。(除了终结方法外,其余方法均为非终结 方法。)

备注:本小节之外的更多方法,请自行参考API文档。

1.3 Stream注意事项(重要)


1. Stream只能操作一次
2. Stream方法返回的是新的流
3. Stream不调用终结方法,中间的操作不会执行

  1. package com.itheima.demo05stream;
  2. import java.util.stream.Stream;
  3. public class Demo03StreamNotice {
  4. public static void main(String[] args) {
  5. Stream<String> stream = Stream.of("aa", "bb", "cc");
  6. // 1. Stream只能操作一次
  7. long count = stream.count();
  8. long count2 = stream.count();
  9. // 2. Stream方法返回的是新的流
  10. Stream<String> limit = stream.limit(1);
  11. System.out.println("stream" + stream);
  12. System.out.println("limit" + limit);
  13. // 3. Stream不调用终结方法,中间的操作不会执行
  14. stream.filter((s) -> {
  15. System.out.println(s);
  16. return true;
  17. }).count();
  18. }
  19. }

1.4 小结


我们学习了Stream的常用方法,我们知道Stream这些常用方法可以分成两类,终结方法,函数拼接方法

Stream的3个注意事项:

1. Stream只能操作一次
2. Stream方法返回的是新的流
3. Stream不调用终结方法,中间的操作不会执行