1.1 从迭代到流的操作

流与集合的差异:

  1. 流并不存储其元素
  2. 流的操作不会修改其数据源
  3. 流的操作是尽可能惰性执行的 ```java package streams;

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List;

/**

  • Created by ql on 2022/5/30 */ public class CountLongWords { public static void main(String[] args) throws IOException {

    1. var contents = new String(Files.readAllBytes(Paths.get("D:\\IdeaProjects\\java-study\\gutenberg\\alice30.txt")), StandardCharsets.UTF_8);
    2. List<String> words = List.of(contents.split("\\PL+"));
    3. long count = 0;
    4. for (String w : words) {
    5. if (w.length() > 12)
    6. count++;
    7. }
    8. System.out.println(count);
    9. count = words.stream().filter(w -> w.length() > 12).count();
    10. System.out.println(count);
    11. count = words.parallelStream().filter(w -> w.length() > 12).count();
    12. System.out.println(count);

    } }

  1. 运行结果:<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/27178439/1653886306746-4f0e0468-c33e-4289-a4e8-20d5d6ac36ee.png#clientId=ua6d06c7b-ee01-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=215&id=u644b5aa2&margin=%5Bobject%20Object%5D&name=image.png&originHeight=215&originWidth=832&originalType=binary&ratio=1&rotation=0&showTitle=false&size=28689&status=done&style=none&taskId=u0202faaf-a640-4f93-952d-2ab3138f649&title=&width=832)
  2. ```java
  3. //产生一个流,其中包含当前流中满足p的所有元素
  4. Stream<T> filter(Predicate<? super T> predicate);
  5. //产生当前流中元素的数量。这是一个终止操作
  6. long count();
  1. //产生当前集合中所有元素的顺序流或并行流
  2. default Stream<E> stream()
  3. default Stream<E> parallelStream()

1.2 流的创建

  1. package streams;
  2. import java.io.IOException;
  3. import java.math.BigInteger;
  4. import java.nio.charset.StandardCharsets;
  5. import java.nio.file.FileSystems;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. import java.util.List;
  10. import java.util.stream.Collectors;
  11. import java.util.stream.Stream;
  12. import java.util.stream.StreamSupport;
  13. /**
  14. * Created by ql on 2022/5/30
  15. */
  16. public class CreatingStreams {
  17. public static <T> void show(String title, Stream<T> stream){
  18. final int SIZE = 10;
  19. List<T> firstElements = stream.limit(SIZE + 1).collect(Collectors.toList());
  20. System.out.print(title + ":");
  21. for (int i = 0; i < firstElements.size(); i++) {
  22. if (i > 0)
  23. System.out.print(",");
  24. if (i < SIZE)
  25. System.out.print(firstElements.get(i));
  26. else
  27. System.out.print("...");
  28. }
  29. System.out.println();
  30. }
  31. public static void main(String[] args) throws IOException {
  32. Path path = Paths.get("D:\\IdeaProjects\\java-study\\gutenberg\\alice30.txt");
  33. String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
  34. Stream<String> words = Stream.of(contents.split("\\PL+"));
  35. show("words", words);
  36. // 产生一个元素为给定值的流
  37. Stream<String> song = Stream.of("gently", "down", "the", "stream");
  38. show("song", song);
  39. //产生一个不包含任何元素的流
  40. Stream<String> silence = Stream.empty();
  41. show("silence", silence);
  42. //产生一个无限流,它的值是通过反复调用函数而构建的
  43. Stream<String> echos = Stream.generate(() -> "Echo");
  44. show("echos", echos);
  45. Stream<Double> randoms = Stream.generate(Math::random);
  46. show("randoms", randoms);
  47. //public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
  48. // 产生一个无限流,它的元素包含seed,在seed上调用f产生的值、在前一个元素上调用f产生的值
  49. Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
  50. show("integers", integers);
  51. // 产生一个流,元素是指定文件中的行,并指定字符集
  52. try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)){
  53. show("lines", lines);
  54. }
  55. Iterable<Path> iterable = FileSystems.getDefault().getRootDirectories();
  56. Stream<Path> rootDirectories = StreamSupport.stream(iterable.spliterator(), false);
  57. show("rootDirectories", rootDirectories);
  58. }
  59. }

运行结果:
image.png

1.3 filter、map和flatMap方法