This post shows how to use Java Stream Reduce with example codes. The idea of the
reduce operation is the generation of a single result from a collection of values or objects. It is similar to the
min and
max operations exemplified on Java 8 Get the Min
and Max
values in a Stream.
Java 8 Stream Reduce Example
Consider the following Java codes that use Stream reduce.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | package com.turreta.stream.reduce; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; public class ReduceTest { List<Student> studentList; static class Student { private String name; private double grade; public Student(String name, double grade) { super(); this.name = name; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getGrade() { return grade; } public void setGrade(double grade) { this.grade = grade; } } @Before public void before() { studentList = Arrays.asList(new Student("Andrew", 85), new Student("Steven", 95), new Student("Ferdinand", 80), new Student("Arthur", 91)); } @Test public void testReduceSum() { Student tmpSum = this.studentList.stream().reduce(new Student("tmp", 0), (tmp, studentObj) -> { tmp.setGrade(tmp.getGrade() + studentObj.getGrade()); return tmp; }); assertTrue(tmpSum.getGrade() == 351); } @Test public void testReduceAverage() { Student tmpAverage = this.studentList.stream().reduce(new Student("tmp", 0), (tmp, studentObj) -> { tmp.setGrade(tmp.getGrade() + studentObj.getGrade()); return tmp; }); tmpAverage.setGrade(tmpAverage.getGrade() / this.studentList.size()); assertTrue(tmpAverage.getGrade() == 87.75); } } |