Java 8 Streams Java Java API
Interface:
java.util.stream.LongStream
Methods:
These terminal operation performs a reduction on the elements.
long reduce(long identity,
LongBinaryOperator op)
Parameters:identity - the identity value for the accumulating functionop - 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); } }
Output30
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); } }
Outputwrong: 27 correct: 29
|
|