Java 8 Collectors: reducing Example
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)
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; } }
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())); } }
Class:A Age:23 Name:Ram Class:B Age:22 Name:Mohan