1、介绍
- Stream流是用于操作数据源如集合、数组等所生成的元素序列;集合是用于存储数据,而流是用于对集合内的数据进行计算。
- Stream不是数据结构,不会保存数据。
- Stream不会修改原来的数据源,它会将操作后的数据保存到另外一个新的对象中。
- Stream是惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。
- Stream可以帮助我们更加聚焦于我们要做的事,而不需要去关注具体做的过程,简化代码,提高开发效率。
如,我们要获取一个类实现的所有接口,并将其打印输出:
Class<ArrayList> arrayListClass = ArrayList.class;
Class<?>[] interfaces = arrayListClass.getInterfaces();
for(Class clazz: interfaces){
System.out.println(clazz.getName());
}
复制代码
而要达到同样的效果,我们不需要使用 for 循环同样也可以实现。
Class<ArrayList> arrayListClass = ArrayList.class;
Class<?>[] interfaces = arrayListClass.getInterfaces();
Arrays.stream(interfaces).forEach(clazz -> System.out.println(clazz.getName()));
复制代码
2、Stream的操作流程
-
<