I’ve got a problem to solve, where I need to create an accounting and bookkeeping solutions part in Java (just the backend, for now). They require the system to store previous prices of given products, so I decided to go with a HashMap<Date,Integer>.
Now problem is, the system has to be able to retrieve prices in given times, for accounting, tracing back purchases (the order stores the item, and the purchase time, so it can be looked back easily). It would be all good, but if the purchase date does not match the price setting date, the simple get method returns null. And so far I haven’t been able to logic out a search method what looks for the first previous date before the purchase date, to return the price.
Is there any suggested way to solve this?
I would recommend you to check
TreeMap.To get the closest date prior to the
dateyou would look it up like this:A break down of the above:
previous = map.headMap(date, true)returns all the previous entries (including date)closestMatchingKey = previous.lastKey()returns the last key in that (above) mapmap.get(closestMatchingKey)returns that match (ornullif none)Example:
Outputs: