Is there a Java function for computing the Gini coefficient?

Viewed 468

I was wondering whether there is a Java function, either built-in to Java, or in an "offical" library such as Apache Commons Math, which computes the Gini coefficient.

From Wikipedia → Gini coefficient:

In economics, the Gini coefficient, sometimes called the Gini index or Gini ratio, is a measure of statistical dispersion intended to represent the income or wealth distribution of a nation's residents, and is the most commonly used measurement of inequality.

1 Answers

I'm not aware of one. But then writing one is pretty trivial!

double gini(List<Double> values) {
    double sumOfDifference = values.stream()
        .flatMapToDouble(v1 -> values.stream().mapToDouble(v2 -> Math.abs(v1 - v2))).sum();
    double mean = values.stream().mapToDouble(v -> v).average().getAsDouble();
    return sumOfDifference / (2 * values.size() * values.size() * mean);
}
Related