Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top