Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap values calculation without iterating

Tags:

java

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));
like image 479
user2684215 Avatar asked Sep 11 '26 21:09

user2684215


2 Answers

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

like image 116
Jon Skeet Avatar answered Sep 13 '26 11:09

Jon Skeet


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.

like image 36
arshajii Avatar answered Sep 13 '26 09:09

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!