/** * Iterates a collection, and sums the Money elements contained in the specified property of each * object. * * <p>Nulls are excluded from the addition. * * @param <T> Type of elements in the collection. * @param collection Collection to iterate. * @param clazz Type of elements in the collection. * @param property Name of the property that contains the money element. * @param currency Currency of the money elements. * @return Returns the sum. */ public static <T> Money sum( Collection<T> collection, Class<T> clazz, String property, Currency currency) { PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(clazz, property); MoneyCalculator calc = new MoneyCalculator(currency, false); for (T t : collection) { Money money = (Money) JavaBeanUtils.getProperty(pd, t); if (money != null) { calc.add(money); } } return calc.getResult(); }
/** * Calculates a {@link Money} field that is calculated as a percentage of another money field in a * collection of elements . <br> * This method iterates a collection and sets a new value to a specified property of each element. * The new value is the result of a calculation. <br> * The calculation of each row takes into account the remainder that was created by the rounding * that took place during the previous calculation, due to rounding the result to the decimal * digits defined by the currency. <br> * * @param collection Collection with the elements. * @param clazz Class of each element in the collection. * @param prc Percentage being applied on the calculation. * @param amountProperty Name of the property that produces the base amount for the calculation. * @param calculatedProperty Name of the property that is filled with the result of the * calculation. * @param currency Currency. * @param <T> Type of elements in the collection. */ public static <T> void calcPercentage( Collection<T> collection, Class<T> clazz, BigDecimal prc, String amountProperty, String calculatedProperty, Currency currency) { PropertyDescriptor amountPd = JavaBeanUtils.getPropertyDescriptor(clazz, amountProperty); PropertyDescriptor calculatedPd = JavaBeanUtils.getPropertyDescriptor(clazz, calculatedProperty); MoneyCalculator calc = new MoneyCalculator(currency, true); for (T t : collection) { Money amount = (Money) JavaBeanUtils.getProperty(amountPd, t); if (amount != null) { calc.set(amount); Money calculated = calc.multiply(prc); JavaBeanUtils.setProperty(calculatedPd, calculated, t); } } }