from
https://blog.chou.it/2014/03/java-8-new-features/
from
https://docs.oracle.com/javase/8/docs/api
from
http://blog.csdn.net/kimylrong/article/details/47255123
from
https://www.ibm.com/developerworks/cn/java/j-lo-jdk8newfeature/
from
http://developer.51cto.com/art/201311/417455.htm
Collections Streaming
集合之流式操作
Java
8 引入了流式操作(Stream),通过该操作可以实现对集合(Collection)的并行处理和函数式操作。根据操作返回的结果不同,流式操作分为中间操作和最终操作两种。最终操作返回一特定类型的结果,而中间操作返回流本身,这样就可以将多个操作依次串联起来。根据流的并发性,流又可以分为串行和并行两种。流式操作实现了集合的过滤、排序、映射等功能。
Stream
和 Collection 集合的区别:Collection 是一种静态的内存数据结构,而
Stream 是有关计算的。前者是主要面向内存,存储在内存中,后者主要是面向
CPU,通过 CPU 实现计算。
public interface Collection extends
Iterable
default interface method
default Stream stream(): Returns a sequential
Stream with this collection as its source.
default Stream parallelStream(): Returns a
possibly parallel Stream with this collection as its source. It is
allowable for this method to return a sequential stream.
Package
java.util.stream
Classes to support
functional-style operations on streams of elements, such as
map-reduce transformations on collections.
串行和并行的流
流有串行和并行两种,串行流上的操作是在一个线程中依次完成,而并行流则是在多个线程上同时执行。并行与串行的流可以相互切换:通过
stream.sequential() 返回串行的流,通过
stream.parallel()
返回并行的流。相比较串行的流,并行的流可以很大程度上提高程序的执行效率。
Stateful
intermediate operation中间操作: filter(), sorted(), map(), distinct(),
subStream()
该操作会保持
stream 处于中间状态,允许做进一步的操作。它返回的还是的
Stream,允许更多的链式操作。
Terminal operation 终止操作: count(), allMatch(), anyMatch(), findAny(),
findFirst(), toArray(), forEach(), reduce()
该操作必须是流的最后一个操作,一旦被调用,Stream
就到了一个终止状态,而且不能再使用了。
Streamdistinct()
Returns a stream
consisting of the distinct elements (according to
Object.equals(Object)) of this stream.
Streamfilter(Predicate