《Java核心技术 卷II》流的创建

流的创建

Collection接口中stream方法可以将任何集合转换为一个流。

用静态Stream.of转化成数组。

Stream words = Stream.of(contents.split("\\PL+"));

of方法具有可变长参数,可以构建具有任意数量的流。

使用Array.stream(array,from,to)可以用数组一部分创建一个流。

String.empty方法创建不包含任何元素的流。

等等,详细看代码注释。

创建流的各种方式

java 复制代码
package streams;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class CreatingStreams {

    public static <T> void show(String title, Stream<T> stream) {
        final int SIZE = 10;
        List<T> firstElements = stream.limit(SIZE + 1).toList();
        System.out.print(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 = Path.of("./resources/alice.txt");
        var contents = Files.readString(path);
//        当使用\\PL+来分割字符串时,实际上是按照非字母字符序列来进行分割。
//        例如,对于字符串"hello,world!123",
//        使用\\PL+作为分割模式,会将字符串分割成["hello", "world", "123"]。
        //可变参数,本质上是一个数组
        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);
        //产生一个无限流,反复调用Supplier<T>产生
        Stream<String> echos = Stream.generate(()->"Echo");
        show("echos", echos);
        //同上,生成随机数组之类的很好用
        Stream<Double> randoms = Stream.generate(Math::random);
        show("random", randoms);
        //产生无限流,通过动作,中间可以增加参数表示是否符合条件
        Stream<BigInteger> integers = Stream.iterate(
                BigInteger.ONE, t -> t.add(BigInteger.ONE));
        show("integers", integers);
        //String类由所有行构成的流
        Stream<String> greetings = "你好\n有趣的\n阿立".lines();
        show("greetings", greetings);
        //通过匹配模式返回流
        Stream<String> wordsAnotherWay = Pattern.compile("\\PL+").splitAsStream(contents);
        show("wordsAnotherWay", wordsAnotherWay);
        //指定文件中的行产生的流
        try(Stream<String> lines = Files.lines(path)){
            show("lines", lines);
        }
        //由给定分割迭代器产生的值组成的流
        Iterable<Path> iterable = FileSystems.getDefault().getRootDirectories();
        //由可分割的迭代器产生的流。
        Stream<Path> rootDirectories = StreamSupport.stream(iterable.spliterator(), false);
        show("rootDirectories", rootDirectories);
        //由可分割的迭代器产生的流。
        Iterator<Path> iterator = Path.of("D:\\主流技术\\书").iterator();
        Stream<Path> pathComponents = StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
        show("pathComponents", pathComponents);
    }

}

结果:

相关推荐
酷在前行19 分钟前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
ThsPool21 分钟前
【ENVI二次开发学习整理 04】ENVI功能扩展与二次开发
java·前端·javascript
cxr82829 分钟前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
赤壁小虾33 分钟前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
废弃的小码农2 小时前
功能测试--Day07--Python编程基础
开发语言·python
青山木2 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Jul1en_2 小时前
【Claude Code Compact】源码级别的学习上下文压缩
java·前端·学习·github·ai编程
fengci.2 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
XWalnut2 小时前
SpringBoot快速入门
java·spring boot·后端
前端 贾公子2 小时前
第06章:结构化输出 (上)
java·服务器·前端