user2684215
user2684215

Reputation: 73

HashMap values calculation without iterating

I have below map, i want to divide rate with each value in charges map without iterating each entry and constructing new map.Is it possible?

final String rate="2";
Map<String,BigDecimal> charges=new HashMap<String,BigDecimal>();
charges.put("tax", new BigDecimal(22));
charges.put("vat", new BigDecimal(200));
charges.put("gross", new BigDecimal(100));
charges.put("principal", new BigDecimal(150));

after division

charges.put("tax", new BigDecimal(11));
charges.put("vat", new BigDecimal(100));
charges.put("gross", new BigDecimal(50));
charges.put("principal", new BigDecimal(75));

Upvotes: 3

Views: 792

Answers (2)

arshajii
arshajii

Reputation: 129497

BigDecimal is immutable, so you have to replace the values in the map with new instances. You don't need to construct a new map, however (but you do need to iterate):

final BigDecimal divisor = new BigDecimal(rate);

for (Entry<?, BigDecimal> e : charges.entrySet()) {
    e.setValue(e.getValue().divide(divisor));
}

Although I suspect that @JonSkeet is correct about using a map at all; a class containing fields corresponding to the keys of your map seems to be more appropriate here.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500185

Is it possible?

No. In addition, it's not at all clear that you should be using a map for this in the first place. You'd almost certainly be better off with a Charge type with appropriate fields. (That might be 4 fields, or perhaps you could compute some values from other ones.)

You could then add a method to either divide all the relevant field values by a constant amount, or (better IMO) return a new instance of the type with the new values (making the Charge type itself immutable).

Upvotes: 7

Related Questions