一切尽在代码中…
package com.example.demo;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
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.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CreatingStreams{
public static void show(String title,Streamstream){
final int SIZE = 10;
List firstElements = stream.limit(SIZE + 1).collect(Collectors.toList());
System.out.print(title + ":");
for (int i = 0; i < firstElements.size(); i++) {
if (i>0){
System.out.print(",");
}
if (i
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("D:\gutenberg\Test.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);
BigInteger limit = new BigInteger("10000000");
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);
}
//获取当前电脑磁盘目录
Iterable iterable = FileSystems.getDefault().getRootDirectories();
Stream rootDirectories = StreamSupport.stream(iterable.spliterator(), false);
show("rootDirectories",rootDirectories);
Iterator iterator = Paths.get("/usr/share/dict/words").iterator();
Stream pathComponents = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
show("pathComponents",pathComponents);
}
}
执行结果:
words:qwe
,qwert
,qwertyui
,qwertyuiop
,qwertyuiopa
,qwertyuiopas
song:gently
,down
,the
,stream
silence:echos:Echo
,Echo
,Echo
,Echo
,Echo
,Echo
,Echo
,Echo
,Echo
,Echo
,…
randoms:0.5194703437391313
,0.2760670786937688
,0.9965354224646149
,0.6639623038808492
,0.9339684162587291
,0.6456112697530748
,0.21091642790070342
,0.5188216760030755
,0.3721295912299638
,0.5104006449444084
,…
integers:1
,2
,3
,4
,5
,6
,7
,8
,9
,10
,…
wordsAnotherWay:qwe
,qwert
,qwertyui
,qwertyuiop
,qwertyuiopa
,qwertyuiopas
lines:qwe
,qwert
,qwertyui…
,qwertyuiop qwertyuiopa qwertyuiopas
rootDirectories:C:
,D:
,E:
,F:
pathComponents:usr
,share
,dict
,words



