Close

Java 8 Streams - LongStream.reduce Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.LongStream

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

Methods:

These terminal operation performs a reduction on the elements.

long reduce(long identity,
            LongBinaryOperator op)
Parameters:
identity - the identity value for the accumulating function
op - a function for combining two values



OptionalLong reduce(LongBinaryOperator op)

Parameters:
op - a function for combining two values


Examples


package com.logicbig.example.longstream;

import java.util.OptionalLong;
import java.util.stream.LongStream;

public class ReduceExample {

public static void main(String... args) {
OptionalLong optionalLong = LongStream.range(1, 5)
.reduce(ReduceExample::sumOfSquared);
if (optionalLong.isPresent()) {
System.out.println(optionalLong.getAsLong());
}
}

private static long sumOfSquared(long l, long l1) {
return l + (l1 * l1);
}
}

Output

30




package com.logicbig.example.longstream;

import java.util.OptionalLong;
import java.util.stream.LongStream;

public class ReduceExample2 {

public static void main(String... args) {
OptionalLong optionalLong = LongStream.range(2, 5)
.reduce(ReduceExample2::sumOfSquared);
if (optionalLong.isPresent()) {
System.out.println("wrong: " + optionalLong.getAsLong());
}

//using identity method
long result = LongStream.range(2, 5)
.reduce(0, ReduceExample2::sumOfSquared);
System.out.println("correct: " + result);
}

private static long sumOfSquared(long l, long l1) {
return l + (l1 * l1);
}
}

Output

wrong: 27
correct: 29




See Also