Close

Java 8 Streams - IntStream.reduce Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.IntStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.IntStreamIntStreamLogicBig

Methods:

These terminal operation performs a reduction on the elements.

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



OptionalInt reduce(IntBinaryOperator op)

Parameters:
op - a function for combining two values


Examples


package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class ReduceExample {

public static void main(String... args) {
IntStream intStream = IntStream.range(1, 5);
int i = intStream.reduce(0, (a, b) -> (a + b) * 2);
System.out.println(i);
}
}

Output

52




package com.logicbig.example.intstream;

import java.util.OptionalInt;
import java.util.stream.IntStream;

public class ReduceExample2 {

public static void main(String... args) {
IntStream intStream = IntStream.range(1, 5);
OptionalInt optionalInt = intStream.reduce((a, b) -> (a + b) * 2);
if (optionalInt.isPresent()) {
System.out.println(optionalInt.getAsInt());
}
}
}

Output

44




See Also