Close

Java 8 Streams - DoubleStream.collect Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.DoubleStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.DoubleStreamDoubleStreamLogicBig

Method:

<R> R collect(Supplier<R> supplier,
              ObjDoubleConsumer<R> accumulator,
              BiConsumer<R,R> combiner)

This terminal operation performs a mutable reduction operation on the elements of this stream.

Type Parameter:
R - type of the result
Parameters:
supplier - a function that creates a new result container (mutable object) . For a parallel execution, this function may be called multiple times. It must return a fresh value each time.
accumulator - a function for incorporating an additional element into a result.
combiner - a function for combining two values, used in parallel stream, combines the results received from different threads.

Examples


package com.logicbig.example.doublestream;

import java.util.stream.DoubleStream;

public class CollectExample {

public static void main(String... args) {

DoubleStream ds = DoubleStream.of(1.01, 1.2, 1.4, 1.6, 2.4, 2.7);

//collect product of rounded doubles
long result = ds.parallel()
.collect(() -> new long[]{1},
(longs, value) ->
longs[0] = Math.multiplyExact(longs[0], Math.round(value)),
(longs, longs2) ->
longs[0] = Math.multiplyExact(longs[0], longs2[0])
)[0];
System.out.println(result);

}
}

Output

12




See Also