sum ,min ,max etc example using reduce method using Java 8 Stream API
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.stream.Stream;
public class Java8StreamReduceMethodExample {
public static void main(String[] args) {
// sum ,min ,max etc example using reduce method using Java 8 Stream API
Integer[] input = { 1, 22, -1, 10, 2, 3 };
int sum1 = Stream.of(input).reduce(0, Integer::sum);
System.out.println("Sum using Stream reduce() mrthod =" + sum1);
int sum2 = Stream.of(input).reduce(Integer::sum).get();
System.out.println("Sum using Stream reduce() mrthod =" + sum2);
int sum3 = Stream.of(input).reduce(0, (x, y) -> x + y);
System.out.println("Sum using Stream reduce() mrthod =" + sum3);
int sum4 = Stream.of(input).reduce((x, y) -> x + y).orElse(-1);
System.out.println("Sum using Stream reduce() mrthod =" + sum4);
int sum5 = Stream.of(input).reduce(10, (x, y) -> x + y, Integer::sum);
System.out.println("Sum using Stream reduce() mrthod =" + sum5);
// Minimum
int min1 = Stream.of(input).reduce(Integer::min).get();
System.out.println("Min using Stream reduce() mrthod =" + min1);
int min2 = Stream.of(input).reduce((x, y) -> x > y ? y : x).orElse(-1);
System.out.println("Min using Stream reduce() mrthod =" + min2);
// Maximum
int max1 = Stream.of(input).reduce(Integer::max).orElse(-1);
System.out.println("Max using Stream reduce() mrthod =" + max1);
int max2 = Stream.of(input).reduce((x, y) -> x > y ? x : y).orElse(-1);
System.out.println("Max using Stream reduce() mrthod =" + max2);
// longest String using java8 stream api - reduce() method
String[] str = { "Rajesh", "Kumar", "R4R", "Rajesh Kumar" };
String longestString = Stream.of(str).reduce((str1, str2) -> str1.length() > str2.length() ? str1 : str2).orElse(null);
System.out.println("Longest String - " + longestString);
// Smallest String using java8 stream api - reduce() method
String smallestString = Stream.of(str).reduce((str1, str2) -> str1.length() < str2.length() ? str1 : str2)
.orElse(null);
System.out.println("Smallest String - " + smallestString);
}
}