List of usage examples for java.math BigDecimal add
public BigDecimal add(BigDecimal augend)
From source file:com.nzion.util.UtilMisc.java
/** * Assuming theMap not null; if null will throw a NullPointerException *///w ww . j a va2s . com public static <K> BigDecimal addToBigDecimalInMap(Map<K, Object> theMap, K mapKey, BigDecimal addNumber) { Object currentNumberObj = theMap.get(mapKey); BigDecimal currentNumber = null; if (currentNumberObj == null) { currentNumber = ZERO_BD; } else if (currentNumberObj instanceof BigDecimal) { currentNumber = (BigDecimal) currentNumberObj; } else if (currentNumberObj instanceof Double) { currentNumber = new BigDecimal(((Double) currentNumberObj).doubleValue()); } else if (currentNumberObj instanceof Long) { currentNumber = new BigDecimal(((Long) currentNumberObj).longValue()); } else { throw new IllegalArgumentException("In addToBigDecimalInMap found a Map value of a type not supported: " + currentNumberObj.getClass().getName()); } if (addNumber == null || ZERO_BD.compareTo(addNumber) == 0) { return currentNumber; } currentNumber = currentNumber.add(addNumber); theMap.put(mapKey, currentNumber); return currentNumber; }
From source file:com.kysoft.cpsi.audit.service.SelfCheckServiceImpl.java
private BigDecimal getSumValue(Sheet sheet, int columnId, int startRow, int endRow) { BigDecimal result = new BigDecimal("0"); for (int i = startRow; i <= endRow; i++) { result = result.add(parseBigDecimal(POIUtils.getCellFormatValue(sheet.getRow(i).getCell(columnId)))); }/*w w w .j a va2s. c o m*/ return result; }
From source file:com.salesmanager.core.service.tax.TaxService.java
/** * Calculates tax on a BigDecimal price, returns the price with tax * /*from ww w .j a v a 2s. c o m*/ * @param amount * @param customer * @param merchantId * @return * @throws Exception */ @Transactional public BigDecimal calculateTax(BigDecimal amount, long taxClassId, Customer customer, int merchantId) throws Exception { // no tax calculation id taxClassId==-1 if (taxClassId == -1) { return amount; } MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); ConfigurationRequest request = new ConfigurationRequest(merchantId, ShippingConstants.MODULE_TAX_BASIS); ConfigurationResponse response = mservice.getConfiguration(request); String taxBasis = TaxConstants.SHIPPING_TAX_BASIS; // get tax basis MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS); if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax // basis taxBasis = taxConf.getConfigurationValue(); } Collection taxCollection = null; if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) { taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(), customer.getCustomerZoneId(), taxClassId, merchantId); } else { taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(), customer.getCustomerBillingZoneId(), taxClassId, merchantId); } BigDecimal currentAmount = new BigDecimal(0); currentAmount.setScale(2, BigDecimal.ROUND_HALF_UP); if (taxCollection != null) { Iterator i = taxCollection.iterator(); while (i.hasNext()) { TaxRate trv = (TaxRate) i.next(); BigDecimal amountForCalculation = amount; if (trv.isPiggyback()) { amountForCalculation = amountForCalculation.add(currentAmount); } double value = ((trv.getTaxRate().doubleValue() * amountForCalculation.doubleValue()) / 100) + amountForCalculation.doubleValue(); currentAmount = currentAmount.add(new BigDecimal(value)); } } return currentAmount; }
From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java
private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying, Period[] expiries) {// ww w . j av a2 s. c o m ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); } ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); String formattedName = MessageFormatter.format("[{}] {}", underlying, longName); ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (int i = 0; i < expiries.length; i++) { Period bucketPeriod = expiries[i]; ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1)); LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run LocalDate targetExpiry = nowish.plus(bucketPeriod); LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.warn("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] { chosenExpiry, bucketPeriod, targetExpiry }); Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (ExternalId optionTicker : tickersToLoad) { ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (Exception ex) { s_logger.error("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }
From source file:com.dp2345.entity.SetProduct.java
/** * ??/*from w w w .j a v a2s.c o m*/ * * @return ? */ @Transient public BigDecimal getCost() { BigDecimal cost = new BigDecimal(0); if (getSetProductItems() != null) { for (SetProductItem item : getSetProductItems()) { if (item != null && item.getSubCost() != null) { cost = cost.add(item.getSubCost()); } } } return cost; }
From source file:com.dp2345.entity.SetProduct.java
/** * /* w w w. ja v a 2 s. c o m*/ * * @return ? */ @Transient public BigDecimal calculatePrice() { BigDecimal price = new BigDecimal(0); if (getSetProductItems() != null) { for (SetProductItem item : getSetProductItems()) { if (item != null && item.getSubPrice() != null) { price = price.add(item.getSubPrice()); } } } return price; }
From source file:com.autentia.tnt.businessobject.Project.java
public BigDecimal getCostPerProject() { BigDecimal total = new BigDecimal(0); Set<ProjectRole> roles = this.getRoles(); if (roles != null) { for (ProjectRole role : roles) { Set<Activity> activities = role.getActivities(); if (activities != null) { for (Activity activity : activities) { BigDecimal converse = new BigDecimal(activity.getUser().getCostPerHour()); BigDecimal div = new BigDecimal(activity.getDuration()); BigDecimal ret = div.multiply(converse); total = total.add(ret.divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP));// += activity.getDuration() * activity.getUser().getCostPerHour()/ 60 ; }/*from www . jav a 2s.co m*/ } } } return total; }
From source file:com.opengamma.examples.bloomberg.loader.DemoEquityOptionCollarPortfolioLoader.java
private void addNodes(final ManageablePortfolioNode rootNode, final String underlying, final boolean includeUnderlying, final Period[] expiries) { final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); }/*from ww w . j av a2s .c o m*/ final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); final Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName).getMessage(); final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (final ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption .getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); final LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (final Period bucketPeriod : expiries) { final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode( bucketPeriod.toString().substring(1)); final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run final LocalDate targetExpiry = nowish.plus(bucketPeriod); final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.info("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] { chosenExpiry, bucketPeriod, targetExpiry }); final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<>(); for (final BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); final double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); final StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (final ExternalId optionTicker : tickersToLoad) { final ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (final Exception ex) { s_logger.info("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }
From source file:com.salesmanager.checkout.cart.ShoppingCartAction.java
protected void assembleShoppingCartItems(Collection<ShoppingCartProduct> items) throws Exception { /** Initial order **/ // create an order with merchantId and all dates // will need to create a new order id when submited Order order = new Order(); order.setMerchantId(store.getMerchantId()); order.setCurrency(store.getCurrency()); order.setDatePurchased(new Date()); SessionUtil.setOrder(order, getServletRequest()); /******///from w w w .j av a2 s . c om if (items != null & items.size() > 0) { Iterator i = items.iterator(); while (i.hasNext()) { ShoppingCartProduct v = (ShoppingCartProduct) i.next(); // Prepare order OrderProduct orderProduct = CheckoutUtil.createOrderProduct(v.getProductId(), getLocale(), store.getCurrency()); if (orderProduct.getProductQuantityOrderMax() > 1) { orderProduct.setProductQuantity(v.getQuantity()); } else { orderProduct.setProductQuantity(1); } orderProduct.setProductId(v.getProductId()); List<OrderProductAttribute> attributes = new ArrayList<OrderProductAttribute>(); if (v.getAttributes() != null && v.getAttributes().size() > 0) { for (ShoppingCartProductAttribute attribute : v.getAttributes()) { ProductAttribute pAttr = cservice.getProductAttribute(attribute.getAttributeId(), super.getLocale().getLanguage()); if (pAttr != null && pAttr.getProductId() != orderProduct.getProductId()) { LogMerchantUtil.log(store.getMerchantId(), getText("error.validation.product.attributes.ids", new String[] { String.valueOf(attribute.getAttributeId()), String.valueOf(v.getProductId()) })); continue; } if (pAttr != null && pAttr.getProductId() == v.getProductId()) { OrderProductAttribute orderAttr = new OrderProductAttribute(); orderAttr.setProductOptionValueId(pAttr.getOptionValueId()); attributes.add(orderAttr); // get order product value ProductOptionValue pov = pAttr.getProductOptionValue(); if (pov != null) { orderAttr.setProductOptionValue(pov.getName()); } BigDecimal attrPrice = pAttr.getOptionValuePrice(); BigDecimal price = orderProduct.getProductPrice(); if (attrPrice != null && attrPrice.longValue() > 0) { price = price.add(attrPrice); } // string values if (!StringUtils.isBlank(attribute.getTextValue())) { orderAttr.setProductOptionValue(attribute.getTextValue()); } } else { LogMerchantUtil.log(store.getMerchantId(), getText("error.validation.product.attributes.ids", new String[] { String.valueOf(attribute.getAttributeId()), String.valueOf(v.getProductId()) })); } } } BigDecimal price = orderProduct.getProductPrice(); orderProduct.setFinalPrice(price); orderProduct.setProductPrice(price); orderProduct.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(price, store.getCurrency())); orderProduct.setPriceFormated( CurrencyUtil.displayFormatedAmountWithCurrency(price, store.getCurrency())); // original price orderProduct.setOriginalProductPrice(price); if (!attributes.isEmpty()) { CheckoutUtil.addAttributesToProduct(attributes, orderProduct, store.getCurrency(), getLocale()); } Set attributesSet = new HashSet(attributes); orderProduct.setOrderattributes(attributesSet); SessionUtil.addOrderProduct(orderProduct, getServletRequest()); } // end for } // end if // because this is a submission, cannot continue browsing, so that's it // for the OrderProduct Map orderProducts = SessionUtil.getOrderProducts(super.getServletRequest()); // transform to a list List products = new ArrayList(); if (orderProducts != null) { Iterator ii = orderProducts.keySet().iterator(); while (ii.hasNext()) { String line = (String) ii.next(); OrderProduct op = (OrderProduct) orderProducts.get(line); products.add(op); } } OrderTotalSummary summary = super.updateOrderTotal(order, products, store); this.setSummary(summary); }
From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java
@Override public Map<Integer, BigDecimal> findMainBedragen(List<? extends Bedragen> bedragen, String Month) { SimpleDateFormat dt = new SimpleDateFormat("MM/yyyy"); Map<GroepenSrvPojo, BigDecimal> mainBedragenPerGroup = new HashMap<GroepenSrvPojo, BigDecimal>(); for (Bedragen bedrag : bedragen) { if (dt.format(bedrag.getDatum()).equals(Month)) { GroepenSrvPojo mainGroup = new GroepenSrvPojo(GroepenSrvImpl.getHoofdGroep(bedrag.getGroep())); if (mainBedragenPerGroup.containsKey(mainGroup)) { BigDecimal ammount = mainBedragenPerGroup.get(mainGroup); if (bedrag.getGroep().getNegatief().equals(1)) { ammount = ammount.add(bedrag.getBedrag()); } else { ammount = ammount.subtract(bedrag.getBedrag()); }/* w ww . j a va2 s . c om*/ mainBedragenPerGroup.put(mainGroup, ammount); } else { if (bedrag.getGroep().getNegatief().equals(1)) { mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag()); } else { mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag().multiply(new BigDecimal(-1))); } } } } BigDecimal average = new BigDecimal(0); for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) { average = average.add((BigDecimal) bedrag.getValue()); } average = average.divide(new BigDecimal(mainBedragenPerGroup.size()), 2, RoundingMode.HALF_UP); Map<Integer, BigDecimal> result = new HashMap<Integer, BigDecimal>(); result.put(0, average); for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) { result.put(((GroepenSrvPojo) bedrag.getKey()).getPk_id(), (BigDecimal) bedrag.getValue()); } return result; }