简介
动态规约操作会把Stream(流)中元素添加到动态容器中,例如Collectin或StringBuilder。
如果我们想把Stream中的一堆字符串拼接成一个长字符串的话,一个用以下操作:
String concatenated = strings.reduce("", String::concat)
这种方式虽然管用,但是性能不够优秀,时间复杂度是O(N2)。
为了更高效得完成这类任务,Java提出了动态规约。
实现方式collect()函数
collect()函数会以动态规约的方式处理数据,并以集合的形式返回处理后的结果。
三个参数
collect()函数需要三个参数:
- supplier:生成用来保存结果的容器
- accumulator:处理输入数据,数据会经过它的处理后保存到容器中
- combiner:把产生的结果拼接到另一个容器中(用于多线程并行)
A collect operation requires three functions: a supplier function to construct new instances of the result container, an accumulator function to incorporate an input element into a result container, and a combining function to merge the contents of one result container into another. The form of this is very similar to the general form of ordinary reduction:
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
Collector
可以用Collector,把这三个参数结合到一起。
<R,A> R collect(Collector<? super T,A,R> collector)
一个拼接字符串的例子:
ArrayList<String> strings = new ArrayList<>();
for (T element : stream) {
strings.add(element.toString());
}
//三个参数方式改写
ArrayList<String> strings = stream.collect(() -> new ArrayList<>(),
(c, e) -> c.add(e.toString()),
(c1, c2) -> c1.addAll(c2));
//三个参数方式改写
List<String> strings = stream.map(Object::toString)
.collect(ArrayList::new,
ArrayList::add,
ArrayList::addAll);
//Collector改写
List<String> strings = stream.map(Object::toString)
.collect(Collectors.toList());