Close

Java 8 Streams - LongStream.collect Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.LongStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.LongStreamLongStreamLogicBig

Method:

<R> R collect(Supplier<R> supplier,
              ObjLongConsumer<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.longstream;

import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.LongStream;

public class CollectExample {

public static void main(String... args) {
LongStream stream = LongStream.range(1L, 100000L);

//sum of odds
AtomicLong al = stream.filter(i -> i % 3 == 0)
.parallel()
.collect(AtomicLong::new,
(a, lg) -> a.set(a.get() + lg),
(a, b) -> a.set(a.get() + b.get()));
System.out.println(al.get());
}
}

Output

1666683333




package com.logicbig.example.longstream;

import java.util.stream.LongStream;

public class CollectExample2 {

public static void main(String... args) {
LongStream stream = LongStream.range(1L, 100L);

// odds | separated strings
StringBuilder sb = stream.filter(i -> i % 3 == 0)
.parallel()
.collect(StringBuilder::new,
(a, lg) -> a.append("|").append(lg),
(a, b) -> a.append(b.toString()).toString());
System.out.println(sb.toString());
}
}

Output

|3|6|9|12|15|18|21|24|27|30|33|36|39|42|45|48|51|54|57|60|63|66|69|72|75|78|81|84|87|90|93|96|99




See Also