Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a sequential stream in Java 8 use the combiner parameter on calling collect?

If I call collect on a sequential stream (eg. from calling Collection.stream()) then will it use the combiner parameter I pass to collect? I presume not but I see nothing in the documentation. If I'm correct, then it seems unfortunate to have to supply something that I know will not be used (if I know it is a sequential stream).

like image 472
Graeme Moss Avatar asked Jun 13 '14 09:06

Graeme Moss


People also ask

Is Java 8 stream sequential?

Sequential Stream in Java example When we employ a sequential stream, we are not taking use of a multi-core system, even though the underlying system allows for parallel processing. The stream() method in Java 8 returns a sequential stream.

Is Java 8 support parallel and sequential streams?

Parallel streams divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. On the other hand sequential streams work just like for-loop using a single core.

What are the two types of streams offered by Java 8 sequential and parallel sequential and random parallel and random random and synchronized?

Explanation: Sequential stream and parallel stream are two types of stream provided by java.


1 Answers

Keep in mind to develop against interface specifications -- not against the implementation. The implementation might change with the next Java version, whereas the specification should remain stable.

The specification does not differentiate between sequential and parallel streams. For that reason, you should assume, that the combiner might be used. Actually, there are good examples showing that combiners for sequential streams can improve the performance. For example, the following reduce operation concatenates a list of strings. Executing the code without combiner has quadratic complexity. A smart execution with combiner can reduce the runtime by magnitudes.

List<String> tokens = ...; String result = tokens.stream().reduce("", String::concat, String::concat); 
like image 74
nosid Avatar answered Sep 22 '22 13:09

nosid