fonix232
fonix232

Reputation: 2195

Java look up closest previous Date in HashMap

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?

Upvotes: 1

Views: 1747

Answers (3)

Cratylus
Cratylus

Reputation: 54074

What you need is to use a TreeMap and specifically the method NavigableMap#foorEntry (my emphasis):

public Map.Entry floorEntry(K key)

Description copied from interface: NavigableMap Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.

Specified by: floorEntry in interface NavigableMap

Upvotes: 2

dacwe
dacwe

Reputation: 43504

I would recommend you to check TreeMap.

To get the closest date prior to the date you would look it up like this:

return map.get(map.headMap(date, true).lastKey());

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) map
  • map.get(closestMatchingKey) returns that match (or null if none)

Example:

public static void main(String[] args) {

    TreeMap<Date, String> map = new TreeMap<>();

    map.put(new Date(0), "First");
    map.put(new Date(10), "Second");
    map.put(new Date(20), "Third");
    map.put(new Date(30), "Fourth");
    map.put(new Date(40), "Fifth");

    System.out.println(getClosestPrevious(map, new Date(5)));
    System.out.println(getClosestPrevious(map, new Date(10)));
    System.out.println(getClosestPrevious(map, new Date(55)));
}

private static String getClosestPrevious(TreeMap<Date, String> map, Date date) {
    return map.get(map.headMap(date, true).lastKey());
}

Outputs:

First
Second
Fifth

Upvotes: 8

AlexR
AlexR

Reputation: 115328

As far as I understand keys of your map are dates. If so I suggest you to move to TreeMap instead of HashMap and use your custom comparator that implements the logic of "closest" date. the method compare() of your comparator will return 0 when date is close enough to given one without requiring the exact matching.

Upvotes: 0

Related Questions