Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

Reducing

sum(), max(), and min() are known as special cases of reduction. By reduction, we mean an abstraction based on two main statements:

  • Take an initial value (T)
  • Take a BinaryOperator<T> to combine two elements and produce a new value

Reductions can be accomplished via a terminal operation named reduce(), which follows this abstraction and defines two signatures (the second one doesn't use an initial value):

  • T reduce​(T identity, BinaryOperator<T> accumulator)
  • Optional<T> reduce​(BinaryOperator<T> accumulator)

With that being said, we can rely on the reduce() terminal operation to compute the sum of the elements, as follows (the initial value is 0, and the lambda is (m1, m2) -> m1 + m2)):

int total = melons.stream() .map(Melon::getWeight) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content