Java核心技术卷Ⅱ程序清单1-2

P4-6
程序清单1-2 streams/CreatingStreams.java


  1. 代码
  2. 项目结构
  3. 分析
  4. 重要API

1.代码

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CreatingStreams {
    public static  void show(String title, Stream stream){
        final int SIZE = 10;
        List firstElements = stream.limit(SIZE+1).collect(Collectors.toList());
        System.out.print(title+":");
        for(int i=0;i
            if(i>0) System.out.print(",");
            if(i.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/第1章流库/Words.txt");
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

        Stream words = Stream.of(contents.split("\\PL+"));
        show("words",words);
        Stream song = Stream.of("gently","down","the","stream");
        show("song",song);
        Stream silence = Stream.empty();
        show("silence",silence);

        Stream echos = Stream.generate(() -> "Echo");
        show("echos",echos);

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

        Stream integers = Stream.iterate(BigInteger.ONE,n -> n.add(BigInteger.ONE));
        show("integers",integers);

        Stream wordsAnotherWay = Pattern.compile("\\PL+").splitAsStream(contents);
        show("wordsAnotherWay",wordsAnotherWay);

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

Words.txt里随便写几行字符就好了,这里随便提供一个:

abcdefghijklmnopqrstuvwxyz asd efg hij klm ChineseWordsAreNotAvailable
abcdefghijklm!opqrstuvwxyz

2.项目结构

Java核心技术卷Ⅱ程序清单1-2_第1张图片

3.分析

1.程序目的

掌握各种形式流的创建方式。

2.代码片段

void show(String title, Stream stream)方法:

public static  void show(String title, Stream stream){
        final int SIZE = 10;
        List firstElements = stream.limit(SIZE+1).collect(Collectors.toList());
        System.out.print(title+":");
        for(int i=0;iif(i>0) System.out.print(",");
            if(iout.print(firstElements.get(i));
            else System.out.print("…");
        }
        System.out.println();
    }

void show(String title, Stream stream)方法用于打印流。
这里仅解释以下该行:

 List firstElements = stream.limit(SIZE+1).collect(Collectors.toList());

limit方法用于限定流的长度,在这里意即只有(SIZE+1)个元素会从流中取出放入firstElements列表
collect(Collectors.toList())方法将流里的元素收集为List



main方法:

文件输入输出操作(readAllBytes(Path path)方法和Files.lines(Path path, Charset cs)方法)要求我们抛出java.io.IOException

public static void main(String[] args) throws IOException{}

接下来介绍了几种流的创建

  • 从数组到流
Stream words = Stream.of(contents.split("\\PL+"));
  • 从字符串到流(先分割字符串)
Stream<String> wordsAnotherWay = Pattern.compile("\\PL+").splitAsStream(contents);
  • 从文件到流(以行分割)
Stream lines = Files.lines(path, StandardCharsets.UTF_8)

静态的Files.lines方法会返回一个包含了文件中所有行的stream
这个方法会要求抛出IOException异常。

  • 创建不含任何元素的流
Stream<String> silence = Stream.empty();
  • 创建常值流(无限流)
Stream echos = Stream.generate(() -> "Echo");
  • 创建随机数流(无限流)
Stream randoms = Stream.generate(Math::random);

这里Math::random是调用了final类Math的静态方法random()

public final class Math {
    public static double random() {
            return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
        }
    }
  • 创建迭代序列
Stream integers = Stream.iterate(BigInteger.ONE,n -> n.add(BigInteger.ONE));

这会产生0 1 2 3 4 5 ……



4.重要API

java.util.stream.Stream 8


static Stream of(T...values)
产生一个元素为给定值(可变长参数T)的流。

static Stream empty()
产生一个不包含任何元素的流。

static Stream generate(Supplier s)
产生一个无限流,它的值是通过反复调用函数s而构建的。

static Stream iterate(T seed, UnaryOperator f)
产生一个无限流,它的元素包含种子、在种子上调用f产生的值、在前一个元素上调用f产生的值,等等。


java.util.Arrays 1.2


static Stream stream(T[] array, int startInclusive, int endExclusive)
产生一个流,它的元素是由数组中指定范围内的元素构成的。


java.util.regex.Pattern 1.4


Stream splitAsStream(CharSequence input)
产生一个流,它的元素是输入中由该模式界定的部分。


java.nio.file.Files 7


static Stream lines(Path path)
static Stream lines(Path path, Charset cs)
产生一个流,它的元素是指定文件中的行,该文件的字符集默认为UTF-8,或者也可手动指定字符集。


如有谬误或不完善之处,恳请斧正。

你可能感兴趣的:(Java核心技术卷Ⅱ程序清单1-2)