一 Stream 的基本操作
流的中间操作是惰性的,只有在遇到终操作时候,才会执行中间操作。
1.1 创建stream
1. 构建 stream
静态数据构建 stream
// list list.stream(); // array Stream<String> stream = Arrays.stream(array); // Stream.of() Stream.of("a","b","c"); // 合并流 Stream.concat(stream1, stream2);
动态数据构建 stream,使用 StreamBuilder 来构建。
public static void streamBuilder() { Stream.Builder<String> streamBuilder = Stream.builder(); streamBuilder.add("a"); streamBuilder.add("b"); if (Math.random() > 0.5) { streamBuilder.add("c"); } Stream<String> build = streamBuilder.build(); // build后就不能再添加元素,会抛出异常 build.forEach(System.out::println); }
读取文件中文本,例如读取日志流。
注意,该使用方法要保证资源被妥善关闭,避免资源泄露。尝试用 try with resource
public static void loadFile() { Path path = Paths.get("file.txt"); try (Stream<String> lines = Files.lines(path)) { lines.forEach(System.out::println); } catch (IOException e) { throw new RuntimeException(e); } }
2. 基本类型Stream
针对家中基本类型,同样提供了基本数据流,如 IntStream。
public static void intStream(){ IntStream intStream = IntStream.range(1,4); intStream.forEach(System.out::println); // 输出 1,2,3 } // 可以通过 boxed 进行装箱 public static void intStream(){ IntStream intStream = IntStream.range(1,4); Stream<Integer> integerStream = intStream.boxed(); integerStream.forEach(System.out::println); }
tips,如果在进行了 forEach(最终操作)后,就不能在进行 boxed(中间操作),会抛出异常。
