Skip to content

Instantly share code, notes, and snippets.

@jnape
Created August 5, 2012 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/3266786 to your computer and use it in GitHub Desktop.
Save jnape/3266786 to your computer and use it in GitHub Desktop.
Functional solution for computing geometric mean in Java
package com.jnape.dynamiccollection;
import com.jnape.dynamiccollection.lambda.Accumulator;
import static com.jnape.dynamiccollection.factory.DynamicListFactory.list;
import static java.lang.Math.pow;
public class GeometricMean {
public static final Accumulator<Integer, Integer> TIMES = new Accumulator<Integer, Integer>() {
@Override
public Integer apply(Integer product, Integer number) {
return product * number;
}
};
public static Number geometricMean(Integer... numbers) {
return pow(list(numbers).reduce(TIMES), 1f / numbers.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment