Java 8 Collectors: reducing Example

By Arvind Rai, November 30, 2014
Java 8 Collectors.reducing is used to reduce the stream element with the help of Comparator and BinaryOperator. Collectors.reducing returns the Collector with Optional data. Here in this page, we will find the example of Collectors.reducing. Method syntax from Java Doc is as below.
public static <T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op) 
Collectors.reducing returns a collector with Optional class. We need to pass binary operator as BinaryOperator.maxBy and BinaryOperator.minBy. BinaryOperator takes a Comparator as an argument. According to that Comparator and BinaryOperator, stream elements are reduced and finally can be collected as group. For the demo we are using a class as given below.
Student.java
package com.concretepage.util;
public class Student {
    private String name;
    private Integer age;
    private String className;
    public Student(String name,Integer age, String className){
        this.name=name;
        this.age=age;
        this.className = className;
    }
    public String getName() {
        return name;
    }
    public Integer getAge() {
        return age;
    }
    public String getClassName() {
        return className;
    }
}  
Find the complete example to use Collectors.reducing.
ReducingDemo.java
package com.concretepage.util;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
public class ReducingDemo {
    public static void main(String[] args) {
        Student s1 = new Student("Shyam", 22,"A");
        Student s2 = new Student("Ram",23,"A");
        Student s3 = new Student("Mohan",22,"B");
        Student s4 = new Student(null,21,"B");
        List<Student> list = Arrays.asList(s1,s2,s3,s4);
        Comparator<Student> ageComparator = Comparator.comparing(Student::getAge); 
        Map<String, Optional<Student>> eldestByClass = list.stream().collect(Collectors.groupingBy(Student::getClassName, 
                Collectors.reducing(BinaryOperator.maxBy(ageComparator))));
        eldestByClass.forEach((k,v)->System.out.println("Class:"+k+" Age:"+
                ((Optional<Student>)v).get().getAge()+" Name:"+((Optional<Student>)v).get().getName()));
    }
} 
Find the output.
Class:A Age:23 Name:Ram
Class:B Age:22 Name:Mohan 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us