java8流的创建

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tomorrow_fine/article/details/82950191

流的创建有很多方式,废话不多说,看例子就懂了。

public class CreatingSteams {
    /**
     * 显示流
     *
     * @param title
     * @param stream
     * @param <T>
     */
    public static <T> void show(String title, Stream<T> stream) {
        final int SIZE = 10;
        List<T> firstElements = stream.limit(SIZE + 1)
                .collect(Collectors.toList());
        System.out.println(title + ": ");
        for (int i = 0; i < firstElements.size(); i++) {
            if (i > 0) System.out.print(", ");
            if (i < SIZE) System.out.print(firstElements.get(i));
            else System.out.print("...");
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("src/hello.txt");
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        //数组转化为流
        Stream<String> words = Stream.of(contents.split("\\PL+"));
        show("words", words);
        //可变长参数转化为流
        Stream<String> song = Stream.of("gently", "down", "the", "stream");
        show("song", song);
        //创建一个不包含任何参数的流
        Stream<String> silence = Stream.empty();
        show("silence", silence);

        //generate方法接受一个不包含任何引元的函数,创建一个无限流
        Stream<String> echos = Stream.generate(() -> "Echo");
        show("echos", echos);

        Stream<Double> randoms = Stream.generate(Math::random);
        show("randoms", randoms);

        //iterate方法接受一个种子值,以及一个函数,会反复地将该函数应用到之前的结果上。
        Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO,
                n -> n.add(BigInteger.ONE));
        show("integers", integers);

        //splitAsStream按照正则分割产生一个流
        Stream<String> wordsAnotherWay = Pattern.compile("\\PL").splitAsStream(contents);
        show("wordsAnotherWay", wordsAnotherWay);

        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
            show("lines", lines);
        }
    }


}

猜你喜欢

转载自blog.csdn.net/tomorrow_fine/article/details/82950191