Put as a key in the card

Given the collection of the {Price, Quantity} pair, I need to collect all quantities at the same price point. What is the easiest way to achieve it?

Contaminated, it would be possible to implement a solution using a Hashmap with keys, since price and value are aggregated quantities. But as far as I know, Float not a secure key for a Hashmap . Therefore, this decision is error prone.

What is recommended to solve this problem?

+5
source share
2 answers

You can use BigDecimal as a key. That would be safe for hashcode.

You will need to initialize the values ​​so that they have the same scale, for example:

 BigDecimal key = new BigDecimal(Double.toString(price)).setScale(2); 
+8
source

If all prices have a fixed decimal size (for example, 2 digits), you can simply use Long , presenting the price in cents, as a card key.

Using BigDecimal is a bad option because it can lead to rare and hard-to-reach errors - two BigDecimal are equal only if they have the same value and with the same accuracy (thus, 2.0 not equal to 2.00 and 2 - all three will become different keys on the map )

0
source

All Articles