Stream 的创建方式有很多种, 除了最常见的集合创建, 还有其他几种方式.
List 转 Stream
List 继承自 Collection 接口, 而 Collection 提供了 stream() 方法.
- List<Integer> list = Lists.newArrayList(1, 2, 3);
- Stream<Integer> stream = list.stream();
数组转 stream
对于数组, Arrays 提供了 stream() 方法.
- String[] arr = new String[]{"a", "b", "c"};
- Stream<String> stream = Arrays.stream(arr);
Map 转 stream
Map 并不是一个序列, 不是集合, 没办法直接转成 stream(). 但 entrySet() 是 Set, 可以转
- Map<String, Object> map = Maps.newHashMap();
- Stream<Entry<String, Object>> stream = map.entrySet().stream();
直接创建 Stream
Stream 也提供了 API 直接生成一个 Stream, 这个 Stream 大概可以理解成一个 List. 因为内部就是数组实现的.
Stream<Integer> integerStream = Stream.of(1, 2, 3);
读取文件的 Stream
用过 Linux 的就会对其命令行的管道符敬佩不已, 一个管道符就可以源源不断的做处理. 在 Java 里读取文件也可以实现类似的功能.
- long uniqueWords = 0;
- try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) {
- uniqueWords = lines.flatMap(l -> Arrays.stream(l.split(" ")))
- .distinct()
- .count();
- } catch (IOException e) {
- //
- }
通过函数来生成无限流
Stream 提供了 iterate 来生成一个无线序列, 一个基于初始值的无线序列. 可以用 lambda 设置序列的生成规则, 比如每次增加 2.
- Stream.iterate(0, n -> n + 2)
- .limit(10)
- .forEach(System.out::println);
再比如, 斐波那契数列 (Fibonacci sequence)
- Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
- .limit(20)
- .map(t -> t[0])
- .forEach(System.out::println);
Stream 还提供了另一个 generate 方法来生成序列. 接收一个用户指定的生成序列函数 IntSupplier.
- IntSupplier fib = new IntSupplier() {
- private int previous = 0;
- private int current = 1;
- @Override
- public int getAsInt() {
- int oldPrevious = this.previous;
- int nextValue = this.previous + this.current;
- this.previous = this.current;
- this.current = nextValue;
- return oldPrevious;
- }
- };
- IntStream.generate(fib).limit(10).forEach(System.out::println);
来源: https://www.cnblogs.com/woshimrf/p/Java8-build-stream.html