Java 8 Streams Java Java API
Interface:
java.util.stream.IntStream
Method:
<R> R collect(Supplier<R> supplier,
ObjIntConsumer<R> accumulator,
BiConsumer<R,R> combiner)
This method 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.intstream;
import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream;
public class CollectExample {
public static void main(String... args) { IntStream intStream = IntStream.range(1, 10000); AtomicInteger ai = intStream.filter(i -> i % 2 == 0) .parallel() .collect(AtomicInteger::new, (a, b) -> a.set(a.get() + b), (a, b) -> a.set(a.get() + b.get()) ); System.out.println(ai); } }
Output24995000
|
|