2

I have class say for example public class Item { int price; String name; // getters and setters } I have such 1000 or more objects (just example). For each item there is a different price. And All this item objects are in List<Item> my requirement is to get total price (i.e price for item 1 to nth item of the list).

Is there any utility or way by which i can get total for the particular field (i.e total price of all the items). I just give List, ClassName and fieldName I get the total? I know we can get the total by iterating through the list, call get method add all up and store in some variable.?

Thanks in advance.

java_enthu
  • 2,279
  • 7
  • 44
  • 74
  • This question is similar to another one: [question](http://stackoverflow.com/questions/5963847/is-there-possibility-of-sum-of-arraylist-without-looping) – ArtemStorozhuk Dec 14 '11 at 13:19

2 Answers2

2

AFAIK not in the standard JDK, but there are functions for this in many existing libraries. For example with lambdaj you should be able to do sumFrom(objects, on(Object.class).getField())

riffraff
  • 2,429
  • 1
  • 23
  • 32
2

I have just written a simple method which calculates a sum of some properties in list:

public static <E> Integer sum(List<E> obejcts, String propertyName) throws 
        IllegalAccessException, 
        InvocationTargetException, 
        NoSuchMethodException {
    Integer sum = 0;
    for (Object o: obejcts) {
        sum += (Integer)PropertyUtils.getProperty(o, propertyName);
    }
    return sum;
}

For this I use javabeans technology. You can download needed libraries directly from apache site.

Here's example of using it:

public class MyObject {
private int x;

public MyObject() { }

public int getX() { return x; }

public void setX(int x) { this.x = x; }

}

And calculating sum:

List<MyObject> l = new ArrayList<MyObject>();
...
try {
int a = sum(l,"x");
System.out.print(a);
} catch (IllegalAccessException e) {
...
ArtemStorozhuk
  • 8,715
  • 4
  • 35
  • 53