Java – Why is there no reduce in the Guava library?

Why is there no reduce in the Guava library?… here is a solution to the problem.

Why is there no reduce in the Guava library?

I

wanted to use functional programming in my Android application, but since Java8 is not available, I decided to use the Guava library. But apparently there is no REDUCE aggregate in the Guava library. If anyone can explain why this is the case, I’d love to know, but what I need is a workaround.

How do I simulate REDUCE/DROP functional programming functionality in Guava? For example, how to calculate a sum or average on FluentInterface without having to write code from scratch yourself (one of the main principles of functional programming, isn’t it?). )。

Please let me know if you do this with a different library in Android as well.

Solution

Guava doesn’t support this because the anonymous class you need to build ends up being much longer than the traditional imperative for loop. Guava deliberately provides only a limited set of functional programming style features: see, for example https://github.com/google/guava/wiki/FunctionalExplained#Caveats for details.

Let’s assume that Guava does provide this. It has to look like

FluentIterable.from(integers).foldr(
  new BiFunction<Integer, Integer, Integer>() {
    @Override Integer sum(Integer a, Integer b) {
      return a + b;
    }
  }, 0);

… with….

int sum = 0;
for (int value : integers) {
   sum += value;
}

The second version requires much fewer boilerplates. This is not worth it without lambda in the language.

Related Problems and Solutions