1. 流的核心思想:我们可以说明想要完成什么任务,而不是说明如何去实现它,将操作的调度留给具体实现去解决。
2.在处理集合时,通常会迭代遍历他的元素,并在每个元素上执行某项操作。使用流时,相同的操作,处理更简介,具体实现操作看代码。
3. 代码包含普通迭代的过程和流处理的过程。
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Day1Stream {
public static void main(String[] args) throws IOException {
Path path = Paths.get("testData/longWord");
String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
List<String> words = Arrays.asList(contents.split("\\PL+"));
int count = 0;
for (String word : words) {
if (word.length()>=12){
count++;
System.out.println(word);
}
}
System.out.println(count);
count = 0;
count = (int) words.stream()
.filter(word -> word.length()>=12)
.count();
System.out.println(count);
count = 0;
count = (int)words.parallelStream().filter(word -> word.length()>=12).count();
System.out.println(count);
Stream<String> hello = Stream.of("hello", "my", "name");
System.out.println(hello);
Stream<String> stringStream = Stream.of(contents.split("\\PL+"));
}
}
感受一下流操作吧,处理是不是比普通迭代更方便了。