import java.util.Arrays; import java.util.List; public class JavaStreamReducer { public static void main(String[] args) { // Reduce Array to String. String[] people = { "Jack", "Steve", "Alice" }; Arrays.stream(people).reduce((x, y) -> x + " | " + y).ifPresent(s -> System.out.println(s)); // Reduce List to String. System.out.println("\n"); List<String> peoplelist = Arrays.asList(people); peoplelist.stream().reduce((x, y) -> x + "," + y).ifPresent(s -> System.out.println(s)); System.out.println("\n"); // function programming with Stream String greeting = greet(peoplelist); System.out.println(greeting + "\n"); Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); // or with .reduce(0, Integer::sum); System.out.println("Sum of Array: " + sum); System.out.println("\n"); // Reduce List to sum. List<Integer> list = Arrays.asList(numbers); sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println("Sum of List: " + sum); List<Integer> list2 = Arrays.asList(2, 3, 4); // Here result will be 2*2 + 2*3 + 2*4 that is 18. int res = list2.parallelStream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p + q); System.out.println(res); } public static String greet(List<String> names) { String greeting = names.stream().map(name -> name + " ").reduce("Welcome ", (acc, name) -> acc + name); return greeting + "!"; } output: Jack | Steve | Alice Jack,Steve,Alice Welcome Jack Steve Alice ! Sum of Array: 55 Sum of List: 55 18