流提供了一种让我们可以比集合更高的概念级别上指定计算机的数据视图。通过使用流。我们可以说明想要完成什么任务,而不是说明如何实现。
1.从迭代到流操作
在处理集合时,通常会迭代遍历他的元素,并在每个元素上执行具体操作
如一下代码:
String contents = new String(Files.readAllBytes(Path.get("alice.txt")),StandardCharsets.UTF_8);
List<String> words = Arrays.aList(Contents.split("\\PL+"));

long count = 0;
for (String w : words) {
    if (w.length() > 12) {
        count++;
    }
}
使用流的写法如下:
long count = words.stream().filter(w -> w.length() > 12).count();
  • 流不存储其元素。这些元素可能存储在底层的集合中,或者按需生成。
  • 流的操作不会改变其数据源,例如,fliter方法不会从的流中移除元素,而是会生成一个新的流,其中不包含被过滤的元素。
  • 流的操作是尽可能的惰性执行
        List<String> words = Arrays.asList(arrStr.split("\n"));
        long count = words.stream().filter(w -> w.length() > 12).count();
        System.out.print(count+"\n");
        count = words.parallelStream().filter(w -> w.length() > 12).count();
        System.out.print(count+"\n");
java.util.stram.Stream<T>8
Stream<T> filter(Predicate <? super T> p)
生成一个流,其中包含当前流中P的所有元素。
long count()
产生当前流中元素的数量,是一个终止操作。
java.util.Collection<E>1.2
default Stream<E> stram()
default Stream<E> parallStream()
产生当前集合中所有元素的顺序流或者并行流。