《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);
    }

}

结果:

相关推荐
better_liang12 分钟前
每日Java面试场景题知识点之-如何设计分布式锁
java·redis·zookeeper·面试·分布式锁
战族狼魂13 分钟前
集 “自动飞行、智能识别、实时预警、勤务联动” 于一体的高速公路应急车道无人机检测系统方案
java·人工智能·大模型·无人机
一只鹿鹿鹿20 分钟前
信息化项目管理规范(参考Word文件)
java·大数据·运维·开发语言·数据库
Java小白笔记21 分钟前
Linux 手动部署 Oracle JDK 17 完全指南
java·linux·oracle
夕除22 分钟前
实战--2
java·spring boot·spring
XGeFei25 分钟前
python中子线程与主线程的关系
开发语言·python
Chase_______28 分钟前
【Java杂项】final 关键字详解:变量、方法、类限制与引用可变性
java·开发语言·python
ruxingli37 分钟前
Golang iota详解
开发语言·后端·golang
我材不敲代码39 分钟前
Python venv 虚拟环境从入门到精通 + uv 高性能替代工具实战指南
开发语言·python·uv
l1t1 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程18-20
开发语言·python