1

In C# you can do some operations on a list, like this:

return myList.Average(p => p.getValue());

This returns the average of all values. Is there something similar in Java? (That would save me the calculation of a sum and then division by the number of elements?)

Thanks!

Sandman
  • 2,577
  • 2
  • 21
  • 32

5 Answers5

4

No but you could use guava-libraries Function and transform to achieve the same. Here is an example

You can use Lists.transform(...) as well. It will apply the function to the same elements (no copies are created).

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • it would take quite a hack to do this via function and transform (transform is meant to transform n values of one type into n values of another, not collect a common value). How about a code example? – Sean Patrick Floyd Feb 09 '11 at 16:27
1

Lambdaj provides much functionality like this:

Double totalAge = sumFrom(persons).getAge();
//Divide by size to get Average

http://code.google.com/p/lambdaj/wiki/LambdajFeatures

Pablojim
  • 8,542
  • 8
  • 45
  • 69
0

It depends on the type of collection you are creating. I don't think the native java Array types support any functionality like this. However there are other collections that can do these sorts of things, for example Apache Commons Math has a number of structures to do just this sort of thing. Guava is another package with a lot of great Array methods built in.

Another option one could easily implement would be to extend the collection your using. For example:

public class ArrayListExtension extends ArrayList{

  public ArrayListExtension(){}

  public Double average()
  {
     Double sum = 0;
     Iterator<Double> iterator = this.iterator();
     while(iterator.hasNext()){
       sum += iterator.next();
     }
     return sum/this.size();
  }
}

Note: There are no sanity checks built into this. In a real-world implementation you'd want to do some try-catch to make sure that the values are actual numbers.

dmcnelis
  • 2,913
  • 1
  • 19
  • 28
0

You can do the following to get the average of some numbers. Unless you do this lot, there isn't much saving.

public static double average(Collection<Number> coll) {
   double total = 0;
   for(Number n: coll) total += n.doubleValue();
   return total/coll.size();
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Here is a safe version of Peter Lawrey's answer, using BigDecimal:

public static double safeAverage(final Collection<? extends Number> coll){
    BigDecimal dec = BigDecimal.ZERO;
    for(final Number n : coll){
        dec = dec.add(BigDecimal.valueOf(n.doubleValue()));
    }
    return dec.divide(BigDecimal.valueOf(coll.size())).doubleValue();
}

(Not quite safe, however, as BigInteger and BigDecimal also extend Number. Safe if used with any of the Number implementations in java.lang)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588