Summing Numbers with Java 8 Stream.reduce() operation
Hello. In this tutorial, we will explain the Stream.reduce method in java 8.
1. Introduction
Before diving deep into the practice stuff let us understand the reduce()
method in java8 programming.
Stream.reduce()
– Combine the elements of a stream and produces a single result. The method acceptsT identity
andBinaryOperator<T> accumulator
as the arguments. If the identity argument is missing (i.e. no default or initial value is given) it will return an Optional. Represented by the method –T reduce(T identity, BinaryOperator<T> accumulator)
2. Practice
Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Model class
Create a java file in the com.java8.streams.util
package and add the following code. The class will act as a model class for the creation of the employee list.
Employee.java
package com.java8.streams.util; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class Employee { private final UUID id; private final String name; private final double salary; private Employee(UUID id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public static List<Employee> createEmployees() { final List<Employee> employees = new ArrayList<>(); employees.add(new Employee(UUID.randomUUID(), "John", 7500.00)); employees.add(new Employee(UUID.randomUUID(), "Harry", 11000.50)); employees.add(new Employee(UUID.randomUUID(), "Ethan", 9000.00)); employees.add(new Employee(UUID.randomUUID(), "Adam", 12000.00)); employees.add(new Employee(UUID.randomUUID(), "Deborah", 8000.00)); return employees; } public static Employee getMax(Employee e1, Employee e2) { return e1.getSalary() < e2.getSalary() ? e2 : e1; } public UUID getId() { return id; } public String getName() { return name; } public double getSalary() { return salary; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}'; } }
2.2 Understanding the reduce() method
Create a java file in the com.java8.streams
package and add the following code. The class will show the implementation of the reduce()
method in different ways.
Demo.java
package com.java8.streams; import com.java8.streams.util.Employee; import java.util.Arrays; import java.util.List; import java.util.Optional; /* Stream.reduce() - Combine the elements of a stream and produces a single result. Represented the method syntax as - <code>T reduce(T identity, BinaryOperator<T> accumulator);</code> Note - If the identity argument is missing (i.e. no default or initial value is given) it will return an optional. */ public class Demo { // driver code public static void main(String[] args) { System.out.println("----- reduce() in Java8 -----\n"); method1(); method2(); method3(); method4(); method5(); } // stream reduce private static void method1() { List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5); Optional<Integer> optional = integers .stream() .reduce(Integer::sum); System.out.println("Total without seed value = " + optional.orElse(0)); } // stream reduce with default value private static void method2() { List<Integer> integers = Arrays.asList(6, 7, 8, 9, 10); int defVal = 1; int total = integers .stream() .reduce(defVal, Integer::sum); System.out.println("Total with seed value = " + total); } // join collection of strings private static void method3() { List<String> strings = Arrays.asList("one", "two", "three", "four", "five"); Optional<String> optional = strings .stream() .reduce((item1, item2) -> item1 + "$" + item2); System.out.println("Concat string = " + optional.orElse(null)); } // stream reduce with employee private static void method4() { Optional<Double> totalSalary = Employee.createEmployees() .stream() .map(Employee::getSalary) .reduce(Double::sum); System.out.println("Total salary expense = " + totalSalary.orElse(0.0)); } // find maximum among employee objects private static void method5() { Optional<Employee> maxSalaryEmployee = Employee.createEmployees() .stream() .reduce(Employee::getMax); System.out.println("Employee with maximum salary = " + maxSalaryEmployee.orElse(null)); } }
Run the file and if everything goes well the following output will be logged in the IDE console.
Console output
----- reduce() in Java8 ----- Total without seed value = 15 Total with seed value = 41 Concat string = one$two$three$four$five Total salary expense = 47500.5 Employee with maximum salary = Employee{id=c7ffc659-4e9a-474d-a941-9c6e255a28ad, name='Adam', salary=12000.0}
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned the reduce()
method introduced in java8 programming along with the implementation. The method is used to perform the accumulation of a stream and produce a single result. You can download the source code from the Downloads section.
4. Download the Project
This was a tutorial on learning and implementing the Stream.reduce method in java 8.
You can download the full source code of this example here: Summing Numbers with Java 8 Stream.reduce() operation