reducing
The overloaded static methods, Collectors.reducing() return a Collector which perform a reduction on the input stream elements according to the provided binary operator.
<T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)
<T> Collector<T,?,T> reducing(T identity, BinaryOperator<T> op)
<T,U> Collector<T,?,U> reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)
Parameters
op: a BinaryOperator which reduces the input values
identity: The identity value for the reduction, i.e. for all input elements x: op(identity,x) == x
mapper: a mapping function for input type T to U conversion.
Data
private final List<Student> students = Arrays.asList(
new Student("John Smith", "Miami", 7.38, 19),
new Student("Mike Miles", "New York", 8.4, 21),
new Student("Michael Peterson", "New York", 7.5, 20),
new Student("James Robertson", "Miami", 9.1, 20),
new Student("Joe Murray", "New York", 7.9, 19),
new Student("Kyle Miller", "Miami", 9.83, 20)
);
Examples
reducing(op)
public void reducingOp01() {
Stream<Integer> s = Stream.of(5, 10, 20, 50);
Integer i = s.collect(Collectors.reducing((integer, integer2)
-> integer2 - integer)).orElse(-1);
System.out.println(i);
}
Output
35
public void reducingOp02() {
Map<String, Optional<Student>> reduceByCityAvgGrade = students.stream()
.collect(Collectors
.groupingBy(Student::getCity,
Collectors.reducing(BinaryOperator
.maxBy(Comparator
.comparing(Student::getAvgGrade)))));
System.out.println(reduceByCityAvgGrade);
}
Output
{New York=Optional[Student{name='Mike Miles', city='New York', avgGrade=8.4, age=21}], Miami=Optional[Student{name='Kyle Miller', city='Miami', avgGrade=9.83, age=20}]}
reducing(identity, op)
public void reducingOpId01() {
Stream<Integer> s = Stream.of(5, 10, 20, 50);
Integer i = s.collect(Collectors.reducing(1, (integer, integer2)
-> integer2 * integer));
System.out.println(i);
}
Output
50000
public void reducingOpId02() {
Map<String, Student> reduceByCityAvgGrade = students.stream()
.collect(Collectors
.groupingBy(Student::getCity,
Collectors.reducing(new Student("x", "x", 0.0, 0),
BinaryOperator.maxBy(Comparator
.comparing(Student::getAvgGrade)))));
System.out.println(reduceByCityAvgGrade);
}
Output
{New York=Student{name='Mike Miles', city='New York', avgGrade=8.4, age=21}, Miami=Student{name='Kyle Miller', city='Miami', avgGrade=9.83, age=20}}
reducing(identity, mapper, op)
public void reducingOpIdFun01() {
Stream<Integer> s = Stream.of(5, 10, 20, 50).parallel();
String str = s.collect(Collectors.reducing(
"",
x -> Integer.toString(x),
(s1, s2) -> s1 + s2));
System.out.println(str);
}
Output
5102050
public void reducingOpIdFun02() {
double largestAverageGrade = students.stream()
.collect(Collectors.reducing(0.0, Student::getAvgGrade,
BinaryOperator.maxBy(Comparator.comparingDouble(value -> value))));
System.out.println(largestAverageGrade);
}
9.83