Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float as key in map

Tags:

java

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

A dirty-cut, would be to implement solution using Hashmap with keys being price and value being aggregated quantity. But, in my knowledge, Float isn't a safe key for Hashmap. So this solution is error-prone.

What is recommended alternative to solve this problem?

like image 879
Shruti Tiwari Avatar asked Aug 19 '15 15:08

Shruti Tiwari


People also ask

How do you do a float on a map?

put(new Float(a[i]),"cat"); because you value has to be an Integer . To do that you have to declare it as Map<Float,String> m = new HashMap()<Float,String>; .

Can we take pair as a key in map?

You must have an std::pair to be used as your key, and that means following what @andre just commented.

Can I use pair as key in map C++?

These two can be any C++ container class or user-defined class or some other valid class(capable of holding values). So, you can use pair as a key in a map as follows: map<pair<int,string> , long> mp; mp.

What happens if key doesn't exist in map?

When you index a map in Go you get two return values; the second one (which is optional) is a boolean that indicates if the key exists. If the key doesn't exist, the first value will be the default zero value.


1 Answers

You could use BigDecimal as a key. It would be hashcode safe.

You'd have to initialize the values so they have the same scale, for instance:

BigDecimal key = new BigDecimal(Double.toString(price)).setScale(2);
like image 180
Thom Avatar answered Sep 19 '22 20:09

Thom