开发者

Neat way of doing stuff with a List (and such) in Java

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 simila开发者_C百科r in Java? (That would save me the calculation of a sum and then division by the number of elements?)

Thanks!


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).


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


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();
}


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜