Home > Mobile >  Implementing a reduction operation for finding the maximum difference of numbers?
Implementing a reduction operation for finding the maximum difference of numbers?

Time:01-05

I am searching for a suitable stream-based reduction operation to find the maximum difference of a double-list. (Please no solutions with old-style nested for-loops...)

Lets say my double list is
List<Double> list = List.of(1.1, 0.3, 7.8, 1.0, 9.1, 2.3);
then the maximum difference would result to the value
9.1 - 0.3 = 8.8


My first working approach with the use of java-streams is:

List<Double> list = List.of(1.1, 0.3, 7.8, 1.0, 9.1, 2.3);
double maxDiff = list.stream().max(Double::compareTo).get()
    - list.stream().min(Double::compareTo).get();

How to implement a custom accumulator and combiner for the reduction operation Stream.reduce() to achieve the same?

CodePudding user response:

You can avoid streaming over the list twice by using the teeing collector:

double diff = list.stream()
                  .collect(Collectors.teeing(
                          Collectors.reducing(Double::max),
                          Collectors.reducing(Double::min),
                          (max,min) -> max.get() - min.get()));

Or using summaryStatistics

DoubleSummaryStatistics statistics = list.stream()
                                         .mapToDouble(Double::doubleValue)
                                         .summaryStatistics();
double diff = statistics.getMax() - statistics.getMin();

CodePudding user response:

For small list you could possibly make a Cartesian product of the list with itself and calculate the difference of every combination before reducing:

double maxDiff = list.stream()
                     .flatMap(a -> list.stream().map(b -> a - b))
                     .reduce(Double::max)
                     .get();
System.out.println(maxDiff);
  • Related