@Test
public void testConnectionStream(){
List<String> list = new LinkedList<>();
list.add("hello");
list.add("hello java!");
list.add("hello word!");
list.add("are you stupid?");
list.add("nothing is not possible");
list.add("today is a good day");
long begin = System.currentTimeMillis();
Stream<String> stream = list.stream();//获取流对象
System.out.println(System.currentTimeMillis()-begin);
stream.filter(str->str.contains("hello")).toArray();//流对象过滤制定内容(在内部进行了一次迭代筛选?)
System.out.println(System.currentTimeMillis()-begin);
list.forEach(str->System.out.println(str));//新方法forEach迭代
System.out.println(System.currentTimeMillis()-begin);
for (String string : list) {//旧方法
System.out.println(string);
}
System.out.println(System.currentTimeMillis()-begin);
stream.close();
}
然后打印结果:
3
81
hello
hello java!
hello word!
are you stupid?
nothing is not possible
today is a good day
82
hello
hello java!
hello word!
are you stupid?
nothing is not possible
today is a good day
82
可以看出,流的生成并不是很花时间,但是第一次进行内部迭代的时候就很耗时间了,之后的效率跟传统的迭代方式一样? 虽然内部还不知道是什么原理,但是还是建议在只进行少量迭代的时候用传统方式,需要对集合(或者流)进行复杂的数据处理时再用流对象进行处理