Java的性能。forEach(列表::添加)vs。collect(Collectors.toList())
什么更快
List<E> bar = new ArrayList<>();
pan.stream() /* other functions */.forEach(bar::add);
或
List<E> bar = pan.stream() /* other functions */.collect(Collectors.toList());
你可以在下面搜索框中键入要查询的问题!
什么更快
List<E> bar = new ArrayList<>();
pan.stream() /* other functions */.forEach(bar::add);
或
List<E> bar = pan.stream() /* other functions */.collect(Collectors.toList());
# 1 楼答案
我已经测试了这两个场景的大小为1百万的列表。总的来说,顺序流几乎没有区别,但并行流有区别:
在我看来,您不应该使用
forEach
创建列表,因为它违反了函数纯度规则,而且当与并行流一起使用时,collect更有效