java|java8 stream collect方法

参考自:Java Platform SE 8

Mutable reduction A mutable reduction operation accumulates input elements into a mutable result container, such as a Collection or StringBuilder, as it processes the elements in the stream. If we wanted to take a stream of strings and concatenate them into a single long string, we could achieve this with ordinary reduction:String concatenated = strings.reduce("", String::concat) We would get the desired result, and it would even work in parallel. However, we might not be happy about the performance! Such an implementation would do a great deal of string copying, and the run time would be O(n^2) in the number of characters. A more performant approach would be to accumulate the results into a StringBuilder, which is a mutable container for accumulating strings. We can use the same technique to parallelize mutable reduction as we do with ordinary reduction.The mutable reduction operation is called collect(), as it collects together the desired results into a result container such as a Collection. 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 collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner); As with reduce(), a benefit of expressing collect in this abstract way is that it is directly amenable to parallelization: we can accumulate partial results in parallel and then combine them, so long as the accumulation and combining functions satisfy the appropriate requirements. For example, to collect the String representations of the elements in a stream into an ArrayList, we could write the obvious sequential for-each form:ArrayList strings = new ArrayList<>(); for (T element : stream) { strings.add(element.toString()); } Or we could use a parallelizable collect form:ArrayList strings = stream.collect(() -> new ArrayList<>(), (c, e) -> c.add(e.toString()), (c1, c2) -> c1.addAll(c2)); or, pulling the mapping operation out of the accumulator function, we could express it more succinctly as:List strings = stream.map(Object::toString) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); Here, our supplier is just the ArrayList constructor, the accumulator adds the stringified element to an ArrayList, and the combiner simply uses addAll to copy the strings from one container into the other.

其中第一个参数为supplier构建一个新的返回值的实例
第二个参数为将下一个元素放入返回值中
第三个参数为合并返回值的集合
【java|java8 stream collect方法】
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.


    推荐阅读